Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

findOneAndRemove

findOneAndRemove() behaves the same way as remove() does and takes the same


amount of parameters:


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

We just have to define the criteria for which documents we want to delete.


Now, we can also modify the preceding code:


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

Here, I have highlighted the added piece of code. We can also pass on a second parameter


to the callback function which returns the user object being deleted. Now, this is helpful if


we want to display a certain message to the frontend and also add some user attributes


such as name or email of the user. For example, if we want to display a message saying


User with name {x} has been deleted. on the frontend, then we can pass user or other


attributes of user here; in this case, it's the name, to be displayed on the frontend.


The main difference between remove() and findOneAndRemove() is that remove does


not return the documents that were deleted but findOneAndRemove() does. Now we


know when to use these two methods.

Free download pdf