- Full-Stack React Projects
- Shama Hoque
- 213字
- 2021-06-25 21:45:05
Setting up Mongoose and connecting to MongoDB
We will be using the Mongoose module to implement the user model in this skeleton, and also all future data models for our MERN applications. Here, we will start by configuring Mongoose, and utilizing it to define a connection with the MongoDB database.
First, to install the mongoose module, run the following command:
npm install mongoose --save
Then, update the server.js file to import the mongoose module, configure it to use native ES6 promises, and finally use it to handle the connection to the MongoDB database for the project.
mern-skeleton/server/server.js:
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(config.mongoUri)
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${mongoUri}`)
})
If you have the code running in development, saving this update should restart the server that is now integrated with Mongoose and MongoDB.
Mongoose is a MongoDB object modeling tool that provides a schema-based solution to model application data. It includes built-in type casting, validation, query building, and business logic hooks. Using Mongoose with this backend stack provides a higher layer over MongoDB with more functionality including mapping object models to database documents. Thus, making it simpler and more productive to develop with a Node and MongoDB backend. To learn more about Mongoose, visit mongoosejs.com.