Removing a Single Document

The Document object provides the remove() method, which allows you to delete a single document from the model. The syntax for the remove() method on Document objects is shown below:

remove( [callback])

The callback parameter accepts an error as the only argument if an error occurred or the deleted document as the second if the delete was successful.

Listing 16.8 shows an example of using the remove() method to remove the word unhappy. Figure 16.8 shows the output for Listing 16.8.

Listing 16.8 mongoose_remove_one.js: Deleting a document from 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', 'unhappy'),
07   query.exec(function(err, doc){
08     console.log("Before Delete: ");
09     console.log(doc);
10     doc.remove(function(err, deletedDoc){
11       Words.findOne({word:'unhappy'}, function(err, doc){
12         console.log(" After Delete: ");
13         console.log(doc);
14         mongoose.disconnect();
15       });
16     });
17   });
18 });


Image

Figure 16.8 Deleting a document from 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
3.148.103.221