user3513466
user3513466

Reputation: 1

nodeJS Mongoose updating multiple documents & returning the changed values

I'm essentially trying to find all Tasks with a given scaler_ID and then set them their respective scaler_ID to -1 and then return all of the new tasks in the HTTP response.

Here's my code:

api.post('/unassignTasks', function(req, res) {

Task.find({scaler_ID: req.body.scaler_ID}, function(err, tasks) {
    for (var i = 0; i < tasks.length; ++i) {
        tasks[i].scaler_Id = -1;
        console.log(tasks[i]);
        (function(arrayIndex) { 
            tasks[i].save(function(err, result) {
                if (err) { console.log(err); }
            });
        })(i);
        res.send(tasks);
        return;
    }
});

For some reason this won't work and the scaler_ID is not being set to -1 to the elements in the database. Any ideas what is causing this?

Upvotes: 0

Views: 450

Answers (1)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

Proper way by using async.each

//npm install async --save //don't forget to install it first
var async = require('async');

api.post('/unassignTasks', function(req, res) {
    var id = req.body.scaler_ID;
    Task.find({scaler_ID: id }, function(err, tasks) {
        async.each(tasks, function(task, each_cb) {
           task.scaler_Id = -1;
           task.save(each_cb);
        }, function(err) {
           if(err) 
               return res.status(400).send(err);
            res.send(tasks);
        });
    });
}

Upvotes: 1

Related Questions