The save()
method on Collection
objects is kind of interesting. You can use it to insert or update a document in a database. Although it is not as efficient as insert()
or update()
, the save()
method is easier to implement in some circumstances. For example, when you are making ad hoc changes to objects already retrieved from a MongoDB database, you can use save()
without having to implement the query and update objects of the update()
method.
The following is the syntax of the save()
method:
save(doc, [options], [callback])
The doc
parameter is the document object you want to save to the collection. The options
parameter specifies the database change options described in Table 14.1. The callback
parameter is required if you are implementing a write concern in the options. The first parameter of the callback
parameter is an error, and the second parameter is the object that was just saved to the collection.
Typically when you use save()
, the document
object is either a completely new JavaScript object that you want to add to the collection or an object you have already gotten back from the collection and made changes to, and you want to save those changes back to the database.
Listing 14.5 retrieves an object from the database, modifies it, and saves it back to the database, using the save()
method. Lines 9–15 implement the save()
method and callback
. Notice that the save()
method is much simpler to use than the update()
and findAndModify()
methods. Also notice that savedItem
is returned to the callback function and displayed on the console, as shown in Figure 14.5.
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.findOne({type:"supernova"}, function(err, item){
06 console.log("Before Save: ");
07 console.log(item);
08 item.info = "Some New Info";
09 nebulae.save(item, {w:1}, function(err, results){
10 nebulae.findOne({_id:item._id}, function(err, savedItem){
11 console.log("After Save: ");
12 console.log(savedItem);
13 db.close();
14 });
15 });
16 });
17 });
18 });