You can delete a single document from a database by using the findAndRemove()
method. This is very similar to the findAndModify()
method in syntax and application. The following is the syntax for the findAndRemove()
method:
findAndRemove(query, sort, [options], callback)
The query
parameter is a document that is used to identify the document to remove. The request matches the properties and values in the query
parameter with the fields and values of the object, and only those that match the query
parameter are modified.
The sort
parameter is an array of [field, sort_order]
pairs that specify which fields to sort on when finding the item to remove. sort_order
is set to 1
for ascending and -1
for descending. The options
parameter specifies the database change options described in Table 14.1. The first parameter of the callback function is an error, and the second parameter is the results of the document deletion.
Listing 14.8 shows how to delete a document by using the findAndRemove()
method. Lines 9–18 implement the findAndRemove()
method and the callback. The code searches on the items whose type
is planetary
. The sort order [['name', 1]]
specifies to sort the items by name, in ascending order. Notice in the results shown in Figure 14.8 that the Cat's Eye
entry was deleted, but the Helix
entry was not because of the sort order.
Note
To run the code in this exercise, please run the code in exercise 14.1 first to reset the data that may have changed by running other exercises in this chapter.
01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://localhost/", function(err, db) {
03 var myDB = db.db("astro");
04 myDB.collection("nebulae", function(err, nebulae){
05 nebulae.find(function(err, items){
06 items.toArray(function(err, itemArr){
07 console.log("Before Delete: ");
08 console.log(itemArr);
09 nebulae.findAndRemove({type:"Planetary"}, [['name', 1]],
10 {w:1}, function(err, results){
11 console.log("Deleted:
" + results);
12 nebulae.find(function(err, items){
13 items.toArray(function(err, itemArr){
14 console.log("After Delete: ");
15 console.log(itemArr);
16 db.close();
17 });
18 });
19 });
20 });
21 });
22 });
23 });