Open In App

Mongoose update() Function

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

In Mongoose, the update() function is used to modify a document in a MongoDB collection based on a given filter. It updates a document but does not return the updated document itself. This function is part of Mongoose’s Query API and is a powerful tool for managing data in your Node.js applications. In this article, we will walk us through the update() function, its syntax, usage, and common examples.

What is Mongoose update() Function?

The update() function in Mongoose is used to update one or more documents in a MongoDB collection that match a specified condition. This function performs an update operation but does not return the updated document.

Instead, it returns information about the operation, such as how many documents were affected by the update. While update() modifies documents, if you need to get the updated document after modification, you should use the findOneAndUpdate() method instead.

Syntax:

Model.update(query, update, options, callback);

Parameters:

  • query: The filter used to identify which documents to update.
  • update: The update operations to be applied to the documents (e.g., $set, $inc).
  • options (optional): Additional options for the update operation, such as multi (to update multiple documents).
  • callback (optional): A function to handle the response once the update operation is complete.

How to Use Update() Function in Mongoose

The update() function is commonly used when you need to modify one or more fields in a document without needing the updated document as a response. Now that we understand the basics, let’s go through some examples to see how the update() function works in practice.

Example 1: Basic Usage

In this example, we will connect to a MongoDB database and update a user document by changing the user's name. The updated document will not be returned.

Filename: index.js

const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});

// Define the User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});

// Update the user's name from "Amit" to "Gourav"
User.update({ name: "Amit" }, { $set: { name: "Gourav" } }, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Result:", result); // Will show how many documents were updated
}
});

Explanation:

  • The update() function is used to update a document with the name "Amit" to change it to "Gourav".
  • The $set operator is used to specify the field to be updated.

Steps to run the program

Follow these steps to run the Mongoose update() example:

Step 1: Install Mongoose

Make sure you have installed mongoose module using following command:

npm install mongoose

Step 2: Set Up the Project Structure

The project structure will look like this: project structure

Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Database

Step 3: Run the Application

To execute the program, navigate to your project folder and run:

node index.js

Step 4: Verify the Changes

You can use a GUI tool like Robo3T or MongoDB Compass to see the database. After running the update function, you should see the document’s name updated from "Amit" to "Gourav".

new Database

So this is how you can use the mongoose update() function which updates one document in the database without returning it.

Example 2: Using Update with Conditions

In this example, we’ll update the age of users who are over 18 years old.

// Filename: index.js
const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});

// User model definition
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number },
});

// Update users who are over 18 and increase their age by 1
User.update({ age: { $gt: 18 } }, { $inc: { age: 1 } }, { multi: true }, (err, result) => {
if (err) {
console.log('Error:', err);
} else {
console.log('Update Result:', result); // Shows how many documents were updated
}
});

Explanation:

  • The update() function is used with a filter to find users who are older than 18 ({ age: { $gt: 18 } }).
  • The $inc operator is used to increment the age field by 1.
  • The multi: true option allows us to update multiple documents that meet the condition.

Creating a Node.js Application and Installing Mongoose

Before using the update() function or any other Mongoose features, make sure to set up a Node.js application and install the Mongoose module.

Step 1: Create a Node.js Application

To set up a new Node.js application, run the following commands:

mkdir folder_name
cd folder_name
npm init -y
touch index.js

Step 2: Install Mongoose

After initializing the Node.js application, install Mongoose using npm:

npm install mongoose

Step 3: Verify Mongoose Installation

To confirm that Mongoose has been installed, check the version by running:

npm version mongoose

Conclusion

The update() function in Mongoose is a useful tool for updating documents in a MongoDB collection based on a specified condition. While it does not return the updated document, it provides a simple and efficient way to modify data. For more complex scenarios where you need the updated document, consider using methods like findOneAndUpdate(). By understanding how to use the update() function, you can streamline your database operations and make your application more efficient when working with MongoDB through Mongoose.


Next Article

Similar Reads