We have learned about Creating, Reading, and Updating data using Mongoose. Now it is time to look at the final CRUD operation: deleting.
In this chapter we will:
By the end of this chapter, you will be familiar with the different approaches you can take to delete data, and when it is best to use each one. You will also have added the ability to delete users and projects from your MongoosePM application.
By now it will probably come as no surprise that there are a few different methods for deleting data. The methods are:
remove()
: This method deletes one or more documents from the collectionfindOneAndRemove()
: This method finds a single document based on a query object and removes it, passing it to the callback function on successful completionfindByIdAndRemove()
: This method is the same as the findOneAndRemove
method, except that it finds a document based on a provided document IDThe remove()
method can be used in two ways: as a model method, or as an instance method. When using it as a model method, you pass it a query object and it will remove the matching documents. For example:
User.remove({ name : /Simon/ } , function (err){ if (!err){ // all users with 'Simon' in their name were deleted } });
To use the remove()
method as an instance method you operate it after a find operation once you have results returned. For example:
User.findOne({ email : '[email protected]'} , function (err,user){ if (!err){ user.remove( function(err){ // First user with matching email address was removed }); } });
Both the
findByIdAndRemove()
and findOneAndRemove()
methods accept options and can return the deleted document to the callback. We're going to use the findByIdAndRemove
method shortly. So let's have a look at findOneAndRemove
instead. The accepted parameters are as follows:
sort
: set the sort order in case multiple docs are foundselect
: set the document fields to return in the object to the callbackHere's a quick example:
User.findOneAndRemove( {name : /Simon/}, {sort : 'lastLogin', select : 'name email'}, function (err, user){ if (!err) { console.log(user.name + " removed"); // Simon Holmes removed }; } );
Here we search for users whose name contain Simon
, and order them by the date they last logged in, before removing the user who hasn't logged in for the longest time. Once removed, we send their name and e-mail address to the callback to output confirmation of the deletion.
18.217.109.151