Mongoose is a Node.js module that provides developers with the ability to model objects and save
them as MongoDB documents. While MongoDB is a schemaless database, Mongoose offers you the
opportunity to enjoy both strict and loose schema approaches when dealing with Mongoose models.
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, predefine and custom validation, query building, business logic hooks and more, out of the box.
The basic features of Mongoose:
- Mongoose schemas and models
- Verifying your data using predefined and custom validators
- Using middleware to intercept the model’s methods
- Schema indexes, modifiers, and virtual attributes
- Using the model’s methods and performing CRUD operations
Installing the mongoose: npm install –save mongoose, npm install
Contacting to MongoDB:
To connect to MongoDB, we will need to use the MongoDB connection URI.
Since you’re connecting to a local instance, we can skip the username and password and use the
Defining URI in mongoose
Step 1: When a building a real application, saving the URI directly in the config/express.js
file is a bad practice. The best way store application variables are to use your environment
configuration file. Go to your config/env/development.js file and add the following code.
In the real application, we need to define mongoose URI in config/env/production.js
Step 2: We required the Mongoose module and connected to the MongoDB instance using the db property of your configuration object. To In config folder, create a new file named config/mongoose.js , which contains the following code
Add the following code in config/config.js
Step 3: To initialize Mongoose configuration in server.js or app.js in root folder, add the following highlight code as