Open In App

Mongoose findByIdAndUpdate() Function

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

Mongoose’s findByIdAndUpdate() function is a powerful tool for updating documents in MongoDB based on their unique _id. It provides a clean and efficient way to modify data, making it an essential method for performing updates in Node.js applications. In this article, we’ll explore the syntax, parameters, and use cases of the findByIdAndUpdate() function, as well as provide a practical example.

What is Mongoose findByIdAndUpdate() Function?

The findByIdAndUpdate() function in Mongoose is used to find a document by its _id and update it with new data. This method is atomic, meaning it ensures that the find and update operations are performed together, providing reliability and consistency.

It's particularly useful when we need to update a document and already know its unique identifier (_id). The findByIdAndUpdate() function is used to find a matching document, update it according to the update arg, passing any options, and return the found document (if any) to the callback.

Syntax:

Model.findByIdAndUpdate(id, update, options, callback);

Parameters

1. id: The unique_id of the document we want to update.

2. update: An object containing the fields to be updated along with their new values

3. options: (Optional) An object specifying options such as new, upsert, runValidators, etc.

  • new: If set to true, returns the modified document rather than the original. Defaults to false.
  • upsert: If true, creates the document if it doesn’t exist. Defaults to false.
  • runValidators: If true, runs schema validation during the update. Defaults to false.

4. callback: (Optional) A callback function that is called after the update is complete. Alternatively, you can use .then() and .catch() for promises.

Return Value

  • Returns the updated document if new: true is specified, or the original document if new: false (default).
  • If no document is found with the specified id, it returns null.

How to Use Mongoose findByIdAndUpdate()

To use the findByIdAndUpdate() method, we need to have a MongoDB document identified by its unique _id. This method allows us to update the document in a single operation, making it an efficient way to handle updates without needing to fetch the document first. Below are the steps to implement findByIdAndUpdate() in your Node.js application.

Step 1: Install Mongoose

You can visit the link to Install mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Check Mongoose Version

After installing mongoose module, you can check your mongoose version in command prompt using the command.

npm version mongoose

Step 3: Create a Node.js Script

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

Example 1: Using findByIdAndUpdate() in Mongoose

This Node.js script connects to a MongoDB database, defines a User model, and updates the name field of a specific user identified by _id.

// Filename: index.js

const mongoose = require('mongoose');

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

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

// Find a document whose
// user_id=5eb985d440bd2155e4d788e2 and update it
// Updating name field of this user_id to name='Gourav'
const user_id = '5eb985d440bd2155e4d788e2';
User.findByIdAndUpdate(user_id, { name: 'Gourav' },
function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated User : ", docs);
}
});

Explanation:

  • mongoose.connect(): Establishes a connection to your MongoDB database.
  • User Schema: Defines the structure for the User collection.
  • findByIdAndUpdate(): Searches for a document by _id, updates it with new data ({ name: 'Gourav' }), and returns the modified document.

Step 4: Run the program

Open the terminal and navigate to your project folder. Run index.js file using below command:

node index.js

Output: After the function is executed, We can see in the database that the particular user is removed as shown below:

new Database

Why Use findByIdAndUpdate()?

  • Atomic Operations: Ensures that both the find and update operations are performed in a single, atomic transaction.
  • Convenience: Great for use cases where you know the document’s _id and need to update specific fields without fetching the document first.
  • Efficiency: Reduces the need for separate find() and update() calls, improving code efficiency.

Common Use Cases for findByIdAndUpdate()

  1. Updating User Profiles: When updating a user's information, such as their name, age, or address, based on their _id.
  2. Changing Status Fields: Update boolean fields like isActive, isVerified, etc., for a document identified by _id.
  3. Modifying Numeric Fields: For example, incrementing or decrementing a field like likes or votes.

Conclusion

The Mongoose findByIdAndUpdate() function is a powerful method for updating documents by their unique _id in MongoDB. By using this function, we can update specific fields in a document with minimal code and ensure that the operation is atomic and efficient. This function is particularly useful when working with documents in real-time applications, such as updating user profiles or changing status fields. It simplifies our code and improves database performance by combining both finding and updating operations.


Next Article

Similar Reads