How can I keep Mongoose in sync mode?

When I save 4 records, I need to save them one by one, so my code

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 do the save in sync mode?

+5
source share
1 answer

You cannot make moongoose synchronization mode (or anything else with db) since node.js is not created this way. But there are two ways to make them lighter or cleaner.

4 , Moognoose insertMany (http://mongoosejs.com/docs/api.html#model_Model.insertMany). , (http://caolan.imtqy.com/async/docs.html). :

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
    }
});
+3

All Articles