1

I'm using Node.js with MongoDB, to be more specific, MongoLab and Mongoose.

In the DB, I have two collections, pours and users. A user object would be linked to multiple pour objects with a shared cid.

I need to iterate through an array of user objects. But for loop somehow doesn't work with asyn functions that I would like to use to modify my array.

  express.leaderboard = new Array();

  mongoose.Users.find(function(err, users) {
    for (var i = 0; i < users.length; i++) {
      express.leaderboard[express.leaderboard.length] = users[i];
    };

    for (i = 0; i < express.leaderboard.length; i++){
      updateOunces(i, function(a, fluidOunces){
        console.log(a);
        express.leaderboard[a].set('totalOunces', fluidOunces);
      });
    }
  });

And this is my function that would retrieve the total fluidOunces for a user.

function updateOunces(i, callback){

    //console.log(express.leaderboard[b].cid);


    mongoose.Pours.find({
      "cid": express.leaderboard[i].cid
    }).exec(function(err, result) {
      var userOunces = 0.0;
      if (!err) {
        for (i = 0; i < result.length; i += 1) {
            for(j = 0; j < result[i].pour.length; j += 1){
                userOunces += result[i].pour[j].fluidOunces;
            }
        }
        callback(i, userOunces);
        return;
        express.leaderboard[i].set ('totalOunces' , userOunces);

      } else {
        console.log(err)
      };
    });
};

Is there a way to iterate and add a new property to each object in the leaderboard array? Using ASYN? Thank you!

philipxjm
  • 11
  • 1
  • possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Paul Mougel Jul 07 '14 at 23:44

1 Answers1

0

use async library.

Example)

mongoose.Users.find(function(err, users) {
  async.each(users, function(user, callback) {
    // perform updates here, per user.
    callback();
  }, function(err) {
    // everything is complete.
  });
});
tpae
  • 6,286
  • 2
  • 37
  • 64
  • I see how this could work, but how can I make this work with the second function? Note that I'm trying to update my local array with information i retrieve from mongo. So I have two async functions. – philipxjm Jul 08 '14 at 14:21
  • You can nest the async calls, just call the callback a different name. such as `nestedCallback`. – tpae Jul 08 '14 at 16:53