Adding Documents by Using Mongoose

You can add documents to the MongoDB library by using either the create() method on the Model object or the save() method on a newly created Document object. The create() method accepts an array of JavaScript objects and creates a Document instance for each JavaScript object, which applies validation and a middleware framework to them. Then the Document objects are saved to the database. The syntax of the create() method is shown below:

create(objects, [callback])

The callback function of the create() method receives an error for the first parameter if it occurs and then additional parameters, one for each document, saved as additional parameters. Lines 27–32 of Listing 16.4 illustrate using the create() method and handling the saved documents coming back. Notice that the create() method is called on the Model object Words and that the arguments are iterated on to display the created documents in Figure 16.4.

Image

Figure 16.4 Creating new documents in a collection by using Mongoose.

The save() method is called on a Document object that has already been created. It can be called even if the document has not yet been created in the MongoDB database, in which case the new document is inserted. The syntax for the save() method is :

save([callback])

The code in Listing 16.4 also shows the save() method adding documents to a collection using Mongoose. Notice that a new Document instance is created in lines 6–11 and that the save() method is called on that Document instance.

Listing 16.4 mongoose_create.js: Creating new 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 newWord1 = new Words({
07     word:'gratifaction',
08     first:'g', last:'n', size:12,
09     letters: ['g','r','a','t','i','f','c','o','n'],
10     stats: {vowels:5, consonants:7}
11   });
12   console.log("Is Document New? " + newWord1.isNew);
13   newWord1.save(function(err, doc){
14     console.log(" Saved document: " + doc);
15   });
16   var newWord2 = { word:'googled',
17     first:'g', last:'d', size:7,
18     letters: ['g','o','l','e','d'],
19     stats: {vowels:3, consonants:4}
20   };
21   var newWord3 = {
22     word:'selfie',
23     first:'s', last:'e', size:6,
24     letters: ['s','e','l','f','i'],
25     stats: {vowels:3, consonants:3}
26   };
27   Words.create([newWord2, newWord3], function(err){
28     for(var i=1; i<arguments.length; i++){
29       console.log(" Created document: " + arguments[i]);
30     }
31     mongoose.disconnect();
32   });
33 });


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

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