Mongoose findByIdAndUpdate() Function
Last Updated :
24 Mar, 2025
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:

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()
- Updating User Profiles: When updating a user's information, such as their name, age, or address, based on their
_id
. - Changing Status Fields: Update boolean fields like
isActive
, isVerified
, etc., for a document identified by _id
. - 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.
Similar Reads
Mongoose findByIdAndRemove() Function
MongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i
2 min read
Mongoose Queries Model.findByIdAndUpdate() Function
The Mongoose Queries findByIdAndUpdate() function is used to search for a matching document, update it in accordance with the update argument while giving any options, then return the found document (if any) to the callback. Installation of Mongoose Module: Step 1. You can visit the link to Install
7 min read
Mongoose findOneAndDelete() Function
The findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In
5 min read
findByIdAndDelete Method in Mongoose
The findByIdAndDelete() function in Mongoose is a commonly used method to find and remove a document by its unique ID in MongoDB. This method simplifies the process of deleting documents, making it an essential tool for Node.js developers working with MongoDB. Whether you're managing user data, post
4 min read
Mongoose Queries Model.findOneAndUpdate() Function
The Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt
3 min read
Mongoose findOneAndUpdate() Method
The findOneAndUpdate() method in Mongoose is an essential tool for performing atomic updates in MongoDB, ensuring data consistency and integrity. This method is particularly useful in multi-user environments, where concurrent updates might occur on the same document. By using atomic operations, find
8 min read
Mongoose | findOneAndRemove() Function
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin
2 min read
FindById Method in Mongoose
The findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl
4 min read
Mongoose | exists() Function
The exists() function returns true if at least one document exists in the database that matches the given filter, and false otherwise. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter inst
2 min read
Mongoose deleteMany() Function
The deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it
4 min read