Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

Updating records in Mongoose


Let's move on to updating a record in a collection. There are multiple ways to update the


collection records as well, just as in retrieving data from the collections. Updating a
document in Mongoose is the combination of read and create(save) methods. To update


a document, we first need to find that document using the read query of Mongoose, alter
that document, and then save the changes.


findById() and save()

Let's look at an example as follows:


User.findById(1, 'name email', function (error, user) {
if (error) { console.error(error); }

user.name = 'Peter'
user.email = '[email protected]'
user.save(function (error) {
if (error) {
console.log(error)
}
res.send({
success: true
})
})
})

So, the first thing we need to do is find the user document, which we are doing by
findById(). This method returns back the user with the given ID. Now that we have that


user, we can alter whatever we like for this user. In the preceding case, we are changing the


name and email of that person.


Now the important part. The job of updating this user's document is done by the
save() method here. We have already altered the name and email of the user by doing:


user.name = 'Peter'
user.email = '[email protected]'

We are changing the object that was returned via findById() in the first place directly.


Now, when we use user.save(), this method overwrites whatever value it was before for


this user with this new name and email.

Free download pdf