Mongoose is a widely-used Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a powerful framework to interact with MongoDB databases in a more structured and efficient manner. By using Mongoose, developers can easily define schemas, validate data, and perform operations on MongoDB collections with JavaScript.
What is npm and Mongoose?
npm (Node Package Manager) is the default package manager for Node.js that simplifies the management of Node.js modules and packages. It allows developers to easily install, manage, and update the libraries required in their projects. Mongoose is an ODM tool for MongoDB.
It provides a higher-level abstraction for working with MongoDB, enabling us to interact with MongoDB collections using JavaScript objects rather than writing raw MongoDB queries. Mongoose provides useful features like schema validation, middleware support, and built-in querying functions, making it a powerful tool for building scalable applications.
Installation of Mongoose Module
To start using Mongoose in your Node.js project, follow these installation steps:
Step 1: We can install this package by using this command.
npm install mongoose
Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.
npm version mongoose
Step 3: After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.js
Following is the dataset, We are using in the following examples.

Project Structure:

Example Use Cases with Mongoose
Here, we will walk through some common use cases in Mongoose, such as finding, updating, and deleting documents in a MongoDB collection.
1. Finding and Updating a Document in MongoDB Using Mongoose
In this example, we will update the company name to Google for the document with _id
2.
Step to Run Application: Run the application using the following command from the root directory of the project:
node index.js
Example:
//Person.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let PersonSchema = new Schema({
_id: Number,
first_name: String,
last_name: String,
email: String,
gender: String,
city: String,
company_name: String,
})
module.exports = mongoose.model('Person', PersonSchema);
Console Output

After the Query:
Document after the query was run2. Updating a Document in MongoDB Using Mongoose
In this example, we will update the gender field to female in the document with _id
3.
Step to Run Application: Run the application using the following command from the root directory of the project:
node index.js
Example:
//index.js
const Person = require("../mongoose/model/person");
const mongoose = require("mongoose");
let mongoDB = mongoose.connect(
"mongodb://localhost:27017/person", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let db = mongoose.connection;
db.on("error", console.error.bind(console,
"MongoDB Connection Error"));
(async () => {
const res = await Person.updateOne(
{ _id: 3 },
{ gender: "Female" }
);
})();
Before the Query:
Document before the query was runAfter the Query:
Document after the query was run3. Deleting a Document Using Mongoose
In this example, we are trying to delete a document with last_name=Bourgeois. As there is a document that matches the condition, it will be deleted.
Step to Run Application: Run the application using the following command from the root directory of the project:
node index.js
Example:
//index.js
const Person = require("../mongoose/model/person");
const mongoose = require("mongoose");
let mongoDB = mongoose.connect
("mongodb://localhost:27017/person", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let db = mongoose.connection;
db.on("error", console.error.bind(console, "
MongoDB Connection Error"));
(async () => {
const res = await Person.deleteOne
({ last_name: "Bourgeois" });
console.log(`Number of Deleted Documents:
${res.deletedCount}`);
})();
Console Output:
Number of deleted documentsConclusion
Mongoose simplifies the interaction with MongoDB in Node.js applications by providing an easy-to-use API to define schemas, perform validations, and query MongoDB collections. With its powerful features like middleware, validation, and query building, Mongoose becomes an essential tool for Node.js developers working with MongoDB.
Similar Reads
Mongoose Plugins
Plugins are a technique for reusing logic in multiple mongoose schemas. A plugin is similar to a method that you can use in your schema and reuse repeatedly over different instances of the schema. The main purpose of plugins is to modify your schemas. Plugins don't have anything to do with models or
5 min read
Mongoose Populate
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js. One of the most powerful features it provides is the ability to populate document fields with data from other collections. Mongoose's populate() method enables us to reference documents, replacing ObjectId fields with
7 min read
Mongoose Schema API
Mongoose is a powerful ODM (Object Document Mapper) tool for Node.js, specifically designed to work with MongoDB. It offers an easy way to define data models, interact with the database, and enforce data integrity in MongoDB through schemas. In this article, we will explore the Mongoose Schema API,
6 min read
Mongoose Timestamps
Mongoose is a robust Object Data Modeling (ODM) library for Node.js and MongoDB that makes database operations easy. One of the prominent features offered by Mongoose is timestamp support. Timestamps are handled automatically by Mongoose and enable us to record the create and update times of documen
4 min read
Mongoose SchemaType
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB, providing a straightforward way to define the structure of documents, enforce validation, and handle database interactions. Mongoose SchemaTypes are key components that define the types of data stored in MongoDB collections, such
6 min read
Mongoose Validation
Mongoose is an elegant solution for modeling and managing MongoDB data in a Node.js environment. One of its powerful features is data validation which ensures that data is correctly formatted and meets specific business rules before being saved to the database. This article explores Mongoose validat
6 min read
Mongoose Queries
Mongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read
Mongoose Tutorial
Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
Mongoose Virtuals
Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document's collection. Virtuals provide an efficient way to derive and set values based on existing document fields, making them a key tool in Mongoose sch
6 min read
Mongoose Schemas Ids
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a
2 min read