
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In the previous lessons, we learned how to find documents in Mongoose. In this lesson, we will learn how to update documents in Mongoose.
There are many ways to update documents in Mongoose.
The save method is used to update a single document directly after having created or retrieved it.
//
const user = await User.findOne({ name: 'Alice' });
user.age = 30;
await user.save();
In this example, we first find a document with the name 'Alice' and then update the age to 30 by setting the age property of the document. Finally, we call the save method to save the changes to the database.
The update method is used to update multiple documents that match the specified query.
//
const result = await User.updateMany({ name: 'Alice' }, { age: 30 });
In this example, the updateMany method updates all documents that have the name 'Alice' and sets the age to 30.
The update method takes two arguments:
- The query object specifies which documents to update.
- The update object specifies how to update the documents.
The updateOne method updates a single document that matches the specified query.
//
const result = await User.updateOne({ name: 'Alice' }, { age: 30 });
In this example, the updateOne method updates the first document that has the name 'Alice' and sets the age to 30.
The updateOne method takes two arguments:
- The query object specifies which documents to update.
- The update object specifies how to update the documents.
The updateOne method doesn't guarantee that we're updating a specific document. If multiple documents match the query, only the first one will be updated.
If we want to update a specific document using updateOne, we need to make sure our query is specific enough to match only one document.
Upserting is the process of updating a document it exists or creating a new document if it doesn't exist.
When you perform an , one of two things can happen:
To perform an upsert, we can use the upsert option in the update method.
//
const result = await User.updateOne({ name: 'Alice' }, { age: 30 }, { upsert: true });
In this example, the updateOne method updates the first document that has the name 'Alice' and sets the age to 30. If no document with the name 'Alice' exists, a new document will be created with the name 'Alice' and the age 30.
In this lesson, we learned how to update documents in Mongoose. You can:
In the next lesson, we will dive into updating documents using operators!
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.