Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

The only difference here is that the first parameter takes a single integer value, which is the
ID of the document rather than an object. This method also returns the object that is being


updated. So we can use:


User.findByIdAndUpdate(1, { $set: { name: "Sara" } }, function(err){
if(err, user){
console.log(err);
}
res.send(user);
});

Deleting records in Mongoose


Just as there are many ways to create, fetch and update records in Mongoose, it also
provides several ways to delete records from collections as well, such as remove(),


findOneAndRemove(), and findByIdAndRemove(). We can use remove() to remove one


or many documents. We can also find the documents we want to remove first and then use
the remove() command to remove only those documents. If we want to find a specific


document with some criteria, we can use findOneAndRemove(). We can use


findByIdAndRemove() when we know the ID of the document we wish to remove.


remove()

Let's look at a sample for using this method:


User.remove({
_id: 1
}, function(err){
if (err)
res.send(err)
res.send({
success: true
})
})

The first argument of the remove() method takes the criteria for filtering which user we


want to remove. It takes an ID as a parameter. It finds the user with the given ID and


removes the document from the collection. The second parameter is the callback function,
which we talked about before. If something goes wrong with the above operation, it returns


an error, which we can use to better handle the exceptions or the errors that occur in our


application. In the case of success, we can define our own logic as to what to return. In the
preceding case, we are returning { success: true }.

Free download pdf