Step 12
In my database, there is currently a user with the following information
{
_id: "5f9a157610bf5e86746c8eb9",
username: "Matteo27",
password: "yj71YRo4SHookR4",
__v: 0
}
To update a user given their ID, you can use findByIdAndUpdate
:
User.findByIdAndUpdate("5f9a157610bf5e86746c8eb9", {
username: "username-updated",
})
.then((user) => console.log(user))
.catch((err) => console.log(err));
When I run the query above, it returns the same user as before! This is a little confusing! It happens because findByIdAndUpdate
returns the "original" (before update) user document. To change this default behavior, you must pass an option parameter {new: true}
:
User.findByIdAndUpdate(
"5f9a157610bf5e86746c8eb9",
{
username: "username-updated-again",
},
{ new: true }
)
.then((user) => console.log(user))
.catch((err) => console.log(err));
Now you will get the "updated" document:
{
_id: "5f9a157610bf5e86746c8eb9",
username: "username-updated-again",
password: "yj71YRo4SHookR4",
__v: 0
}
We have now covered all the CRUD operations we need for the YouNote API. There are several other query methods which you can learn about here.