Saving Document Changes

You have already seen how to use the save() method to add a new document to a database. You can also use it to update an existing object. Often the save() method is the most convenient to use when working with MongoDB because you already have an instance of the Document object.

The save() method detects whether an object is new, determines which fields have changed, and then builds a database request that updates those fields in the database. Listing 16.5 shows how to implement a save() request. It retrieves the word book from the database and capitalizes the first letter, changing the word and first fields.

Notice that doc.isNew in line 8 reports that the document is not new. Also, line 14 reports the modified fields to the console by using doc.modifiedFields(). These are the fields that will be updated. Figure 16.5 shows the full results.

Listing 16.5 mongoose_save.js: Saving documents 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', 'book'),
07   query.exec(function(err, doc){
08     console.log("Is Document New? " + doc.isNew);
09     console.log(" Before Save: ");
10     console.log(doc.toJSON());
11     doc.set('word','Book'),
12     doc.set('first','B'),
13     console.log(" Modified Fields: ");
14     console.log(doc.modifiedPaths());
15     doc.save(function(err){
16       Words.findOne({word:'Book'}, function(err, doc){
17         console.log(" After Save: ");
18         console.log(doc.toJSON());
19         mongoose.disconnect();
20       });
21     });
22   });
23 });


Image

Figure 16.5 Saving documents 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
52.15.74.25