How to Use findOneAndUpdate in Mongoose: Syntax and Examples
Use
findOneAndUpdate(filter, update, options) in Mongoose to find a single document matching filter and update it with update. You can control the behavior with options, like returning the updated document or creating a new one if none matches.Syntax
The findOneAndUpdate method takes three main parts:
- filter: An object to find the document you want to update.
- update: An object describing the changes to apply.
- options: Optional settings like
newto return the updated document orupsertto create if not found.
javascript
Model.findOneAndUpdate(filter, update, options, callback);
Example
This example shows how to find a user by name and update their age, returning the updated document.
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() { // Find user named 'Alice' and update age to 30 const updatedUser = await User.findOneAndUpdate( { name: 'Alice' }, { $set: { age: 30 } }, { new: true, upsert: true } // return updated doc, create if not found ); console.log(updatedUser); mongoose.connection.close(); } updateUser();
Output
{ _id: ObjectId("..."), name: 'Alice', age: 30, __v: 0 }
Common Pitfalls
Common mistakes when using findOneAndUpdate include:
- Not setting
{ new: true }option, so you get the old document instead of the updated one. - Forgetting
upsert: trueif you want to create a document when none matches. - Not using update operators like
$set, which can cause the entire document to be replaced.
javascript
/* Wrong: replaces whole document without $set */ Model.findOneAndUpdate({ name: 'Bob' }, { age: 25 }); /* Right: updates only the age field */ Model.findOneAndUpdate({ name: 'Bob' }, { $set: { age: 25 } });
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| filter | Finds the document to update | { name: 'Alice' } |
| update | Changes to apply, usually with $ operators | { $set: { age: 30 } } |
| options | Controls behavior like returning updated doc | { new: true, upsert: true } |
| callback | Optional function called after update | function(err, doc) { ... } |
Key Takeaways
Always use { new: true } option to get the updated document returned.
Use update operators like $set to avoid replacing the whole document.
Set upsert: true if you want to create a document when none matches the filter.
findOneAndUpdate returns a promise if no callback is provided, so use async/await.
Remember to close your database connection after operations in scripts.