The Model
object provides an update()
method that allows you to update multiple documents in a collection by using the update
operators described in Table 14.2. The syntax for the update()
method on Model
objects is shown below:
update(query, update, [options], [callback])
The query
parameter defines the query used to identify which objects to update. The update
parameter is an object that defines the update operation to perform on the document. The options
parameter specifies the write preferences, and the callback
parameter accepts an error as the first argument and the number of documents updated as the second.
A nice thing about updating at the model level is that you can use the Query
object to define which objects should be updated. Listing 16.7 shows an example of using the update()
method to update the size
field of words that match the regex /grati.*/
to 0
. Notice that line 11 defines an update
object, but the code adds multiple query options onto the Query
object before executing in line 14. Then the code makes another find()
request, this time using the regex /grat.*/
to show that only what matches the update query actually changes. Figure 16.7 shows the output for Listing 16.7.
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:/grati.*/}, function(err, docs){
07 console.log("Before update: ");
08 for (var i in docs){
09 console.log(docs[i].word + " : " + docs[i].size);
10 }
11 var query = Words.update({}, {$set: {size: 0}});
12 query.setOptions({multi: true});
13 query.where('word').regex(/grati.*/);
14 query.exec(function(err, results){
15 Words.find({word:/grat.*/}, function(err, docs){
16 console.log("
After update: ");
17 for (var i in docs){
18 console.log(docs[i].word + " : " + docs[i].size);
19 }
20 mongoose.disconnect();
21 });
22 });
23 });
24 });