Open In App

npm mongoose

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Peek202210251450

Project Structure:

Screenshotfrom202210310849181

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

Screenshotfrom20221025222413

After the Query:

Screenshot-2024-05-05-at-15041-PM
Document after the query was run

2. 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:

Screenshot-2024-05-05-at-15545-PM
Document before the query was run

After the Query:

Screenshot-2024-05-05-at-15553-PM
Document after the query was run

3. 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:

Screenshotfrom20221026171702
Number of deleted documents

Conclusion

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.


Next Article

Similar Reads