How to Use findByIdAndUpdate in Mongoose: Syntax and Example
Use
findByIdAndUpdate(id, update, options, callback) in Mongoose to find a document by its ID and update it. It returns the original or updated document depending on options like { new: true }.Syntax
The findByIdAndUpdate method takes four main parts:
- id: The unique identifier of the document to update.
- update: An object with the fields and values to change.
- options: Optional settings like
{ new: true }to return the updated document. - callback: Optional function to handle the result or error.
javascript
Model.findByIdAndUpdate(id, update, options, callback)
Example
This example shows how to update a user's name by their ID and get the updated document back.
javascript
const mongoose = require('mongoose'); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true, useUnifiedTopology: true }); // Define a simple User schema const userSchema = new mongoose.Schema({ name: String, age: Number }); const User = mongoose.model('User', userSchema); async function updateUser() { // Create a user to update const user = new User({ name: 'Alice', age: 25 }); await user.save(); // Update the user's name by ID const updatedUser = await User.findByIdAndUpdate( user._id, { name: 'Alice Cooper' }, { new: true } // Return the updated document ); console.log('Updated User:', updatedUser); mongoose.connection.close(); } updateUser();
Output
Updated User: { _id: <ObjectId>, name: 'Alice Cooper', age: 25, __v: 0 }
Common Pitfalls
- Not using
{ new: true }option returns the old document, not the updated one. - Forgetting to handle asynchronous calls with
awaitor callbacks can cause unexpected results. - Passing an invalid ID format causes errors; ensure the ID is a valid ObjectId.
- Not setting
useFindAndModify: falsein Mongoose 5 or earlier can cause deprecation warnings.
javascript
/* Wrong: returns old document */ User.findByIdAndUpdate(userId, { name: 'New Name' }, (err, doc) => { console.log(doc.name); // Old name, not updated }); /* Right: returns updated document */ User.findByIdAndUpdate(userId, { name: 'New Name' }, { new: true }, (err, doc) => { console.log(doc.name); // New Name });
Quick Reference
Remember these key options for findByIdAndUpdate:
| Option | Description |
|---|---|
| new: true | Return the updated document instead of the original. |
| runValidators: true | Run schema validators on the update. |
| upsert: true | Create a new document if none matches the ID. |
| useFindAndModify: false | Avoid deprecation warning in older Mongoose versions. |
Key Takeaways
Use findByIdAndUpdate(id, update, { new: true }) to get the updated document.
Always handle asynchronous calls with await or callbacks.
Validate the ID format to avoid errors.
Use options like runValidators to ensure data integrity.
Set useFindAndModify: false in Mongoose 5 or earlier to prevent warnings.