Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose JS promises? Or how to manage batch save

How do I manage batch save in Mongoose? I saw it may not be possible yet:

  • How can I save multiple documents concurrently in Mongoose/Node.js?

Theres some mention about using some flow control library like q, but I also notice there promises in mongoose, can it be used? Can I do like in jQuery Deferred/Promises

$.when(obj1.save(), obj2.save(), obj3.save()).then ->
    # do something? 
like image 917
Jiew Meng Avatar asked Aug 11 '12 08:08

Jiew Meng


2 Answers

Yes, you can do this with promises. If you were using the Q promise library, you could re-write @matz3's code like:

var tasks = [];

for (var i=0; i < docs.length; i++) {
  tasks.push(docs[i].save());
}

Q.all(tasks)
  .then(function(results) {
    console.log(results);
  }, function (err) {
    console.log(err);
  });

We start all the operations one at a time in the loop, but we don't wait for any of them to complete, so they run in parallel. We add a promise (that acts like a placeholder for the result) to an array. We then wait for all the promises in the array of promises to complete.

Most good Promises/A+ compatible libraries have some equivalent to Q.all

like image 55
ForbesLindesay Avatar answered Oct 04 '22 17:10

ForbesLindesay


mongoose now allows you to choose which Promise implementation.

Here I am using the node.js default system Promise (ES6) baked into nodejs

var mongoose = require('mongoose');
    mongoose.Promise = global.Promise; // use system implementation

Promise.all(obj1.save(), obj2.save(), obj3.save())
.then(function(resultSaves) {

    console.log('parallel promise save result :');
    console.log(resultSaves);
    mongoose.disconnect();

}).catch(function(err) {

    console.log('ERROR on promise save :');
    console.log(err);
    mongoose.disconnect();
});

node --version v4.1.1

[email protected]

like image 42
Scott Stensland Avatar answered Oct 04 '22 16:10

Scott Stensland