papaiatis
papaiatis

Reputation: 4291

How to update multiple Mongo documents manually in NodeJs?

I have a collection of users in MongoDB. I need to generate a token for each user and save it to the database:

var crypto = require('crypto');
db.users.find({}).exec(function(users){
    users.forEach(function(user){
       user.token = crypto.randomBytes(32).toString('hex');
       user.save();
    });
});

I'm always confused about async methods and just can't understand how they work... So this code doesn't work beacuse it exists before the save() calls finish. How would you make it work? How would you wait for all the save()˙calls and print Done! to console?

Thanks!

Upvotes: 1

Views: 76

Answers (1)

alexmac
alexmac

Reputation: 19567

Mongoose find function returns a promise, you can use it to create chain. Promise.all produces promises (or a mix of promises and values), iterate over all the values and return a promise that is fulfilled when all the items in the array are fulfilled.

var crypto = require('crypto');

db.users
    .find({})
    .then(users => {
      var ops = users.map(user => {
       user.token = crypto.randomBytes(32).toString('hex');
       return user.save();
      });
      return Promise.all(ops);
    })
    .then(() => console.log('done'))
    .catch(err => console.log('error' + err));
});

Upvotes: 2

Related Questions