miuosh miuosh - 24 days ago 6
Javascript Question

Add mongoose query (promise) to array and do parallel operations

I'm using mongoose to do some operation in MongoDB. I'd like to seach all tasks created by user, then set value

isPerforming
to
false
and save it.
Documentation says that mongoose query (with
.exec()
function) is promise. There's many tasks so I think to push them to array and do parallel save operations using
Q.all([...])
. The problem is when I try to do
.push()
. My code stops after first
.push()
operation.
Is there any other way to do it?

function stopUserTasks(userid) {

var deferred = Q.defer();
var query = Task.find({'_creator': userid}).exec();

query.then(function(data, err) {
console.log('found: ');
console.log(data);
if (err) {
deferred.reject(err);
}
return data;
})
.then(function(data, err) {

var len = data.length;
var saveTasksPromises = [];

for(var i = len; i--; ) {
console.log(data[i]._id);
saveTasksPromises.push(Task.save({'_id': data[i]._id, 'isPerforming': false}).exec() );
}
return saveTasksPromises;

})
.then(function(data, err) {
console.log(data);

deferred.resolve();
});

return deferred.promise;

}// #stopUserTasks

Answer

Model.save() returns promise actually, so no need to write Model.save().exec() so your line need to be adjusted as follow:

saveTasksPromises.push(Task.save({'_id': element._id, 'isPerforming': false}))

Also using Q.all, the whole function could be as follow:

function stopUserTasks(userid) {
  var deferred = Q.defer();
  var promise = Task.find({'_creator': userid}).exec();

  promise
    .then(function(data) {
      var len = data.length;
      var saveTasksPromises = [];

      for(var i = len; i--; ) {
        saveTasksPromises.push(Task.save({'_id': data[i]._id, 'isPerforming': false}));
      }
      return Q.all(saveTasksPromises);
    })
    .then(function(data) {
      deferred.resolve(data);
    });
    .catch(function(err) {
      deferred.reject(err);
    });
    return deferred.promise;
}