Updating a Single Document

The Document object provides the update() method, which allows you to update a single document by using the update operators described in Table 14.2. The syntax for the update() method on Document objects is shown below:

update(update, [options], [callback])

The update parameter 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.

Listing 16.6 shows an example of using the update() method to update the word gratifaction to gratifactions by setting word, size, and last fields, using a $set operator as well as pushing the letter s on the end of letters by using the $push operator. Figure 16.6 shows the output for Listing 16.6.

Listing 16.6 mongoose_update_one.js: Updating a single document in a collection by using Mongoose


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   var query = Words.findOne().where('word', 'gratifaction'),
07   query.exec(function(err, doc){
08     console.log("Before Update: ");
09     console.log(doc.toJSON());
10     var query = doc.update({$set:{word:'gratifactions',
11                                   size:13, last:'s'},
12                             $push:{letters:'s'}});
13     query.exec(function(err, results){
14       console.log(" %d Documents updated", results);
15       Words.findOne({word:'gratifactions'}, function(err, doc){
16         console.log(" After Update: ");
17         console.log(doc.toJSON());
18         mongoose.disconnect();
19       });
20     });
21   });
22 });


Image

Figure 16.6 Updating a single document in a collection by using Mongoose.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.118.232