![]() |
VOOZH | about |
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.
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.
Model.findByIdAndUpdate(id, update, options, callback);
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.
4. callback: (Optional) A callback function that is called after the update is complete. Alternatively, you can use .then() and .catch() for promises.
new: true is specified, or the original document if new: false (default).id, it returns null.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.
You can visit the link to Install mongoose module. You can install this package by using this command.
npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.
npm version mongooseAfter 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.jsfindByIdAndUpdate() in MongooseThis 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 collection.findByIdAndUpdate(): Searches for a document by _id, updates it with new data ({ name: 'Gourav' }), and returns the modified document.Open the terminal and navigate to your project folder. Run index.js file using below command:
node index.js👁 ImageOutput: After the function is executed, We can see in the database that the particular user is removed as shown below:
👁 new DatabasefindByIdAndUpdate()?_id and need to update specific fields without fetching the document first.find() and update() calls, improving code efficiency.findByIdAndUpdate()_id.isActive, isVerified, etc., for a document identified by _id.likes or votes.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.