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