When I save 4 record, I need to save them one by one, so my code is
a.save(function(){
 b.save(function(){
  c.save(function(){
   d.save(function(){
   }
  }
 }
}
How can I write code like
a.save();
b.save();
c.save();
d.save();
and make the save in sync mode?
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.
Working with save() When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.
The . save() is considered to be an instance method of the model, while the . create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.
Mongoose save with an existing document will not override the same object reference. Bookmark this question. Show activity on this post.
You can't really make sync mode of a moongoose (or anything else with db) as the node.js is not made in that way. But there are two ways to make it easier or more clean.
If all 4 records are the same model, than you can create array of this elements and use Moognoose insertMany (http://mongoosejs.com/docs/api.html#model_Model.insertMany). If not, you can use async library (http://caolan.github.io/async/docs.html). In this case, your code would look like:
var objArr = [a, b, c, d];
async.each(objArr, function(object, callback){
    object.save(function(err){
        if(err) { 
            callback(err)
        }
        else { 
            callback() 
        }
    });
}, function (err){
    if(err) { 
        //if any of your save produced error, handle it here
    } 
    else {
        // no errors, all four object should be in db
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With