Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save Mongoose in sync mode?

Tags:

mongoose

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?

like image 606
Gabriel Tong Avatar asked Jul 14 '16 02:07

Gabriel Tong


People also ask

What is Save () in Mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.

Does update call save in Mongoose?

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.

What is difference between create and save in Mongoose?

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.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question. Show activity on this post.


1 Answers

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
    }
});
like image 101
Jure Malovrh Avatar answered Nov 15 '22 00:11

Jure Malovrh