Introducing MongoDB Chapter 3
There are other methods we can use to update a document in Mongoose.
findOneAndUpdate()
This method can be used when we want to update a single entry. For example:
User.findOneAndUpdate({name: 'Peter'}, { $set: { name: "Sara" } },
function(err){
if(err){
console.log(err);
}
});
As you can see, the first parameter defines the criteria describing the record we want to
update, which, in this case, is the user whose name is Peter. The second parameter is the
object in which we define what attributes of user do we want to update, which is defined
by { $set: { name: "Sara" }. This sets the name of Peter to Sara.
Now, let's make a small alteration to the preceding code:
User.findOneAndUpdate({name: 'Peter'}, { $set: { name: "Sara" } },
function(err, user){
if(err){
console.log(err);
}
res.send(user);
});
Here, notice that I have added a second parameter to the callback function called user.
What this does is that when Mongoose is done updating that document in the database, it
returns the object. This is very useful when we want to make some decisions after we
update the record and want to play with the newly updated document.
findByIdAndUpdate()
This is somewhat similar to findOneAndUpdate(). This method takes an ID as a
parameter, unlike findOneAndUpdate(), where we can add our own criteria, and updates
that document:
User.findByIdAndUpdate(1, { $set: { name: "Sara" } }, function(err){
if(err){
console.log(err);
}
});