The Model
object’s remove()
method allows you to delete multiple documents in a collection by using a single call to the database. The syntax for the remove()
method on Model
objects is shown below:
update(query, [options], [callback])
The query
parameter defines the query used to identify which objects to delete. The options
parameter specifies the write preferences, and the callback
parameter accepts an error as the first argument and the number of documents deleted as the second.
A nice thing about deleting at the model level is that you delete multiple documents in the same operation, saving the overhead of multiple requests. Also, you can use the Query
object to define which objects to update.
Listing 16.9 shows an example of using the remove()
method to delete words that match the regex /grati.*/
expression. Notice that the code pipes multiple query options onto the Query
object before line 13 executes it. The listing displays the number of documents removed, and then another find()
request is made, this time using the regex /grat.*/
to show that only those matching the remove query actually are deleted. Figure 16.9 shows the output for Listing 16.9.
01 var mongoose = require('mongoose'),
02 var db = mongoose.connect('mongodb://localhost/words'),
03 var wordSchema = require('./word_schema.js').wordSchema;
04 var Words = mongoose.model('Words', wordSchema);
05 mongoose.connection.once('open', function(){
06 Words.find({word:/grat.*/}, function(err, docs){
07 console.log("Before delete: ");
08 for (var i in docs){
09 console.log(docs[i].word);
10 }
11 var query = Words.remove();
12 query.where('word').regex(/grati.*/);
13 query.exec(function(err, results){
14 console.log("
%d Documents Deleted.", results);
15 Words.find({word:/grat.*/}, function(err, docs){
16 console.log("
After delete: ");
17 for (var i in docs){
18 console.log(docs[i].word);
19 }
20 mongoose.disconnect();
21 });
22 });
23 });
24 });