1

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!

1 Answer 1

2

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));
});
Sign up to request clarification or add additional context in comments.

3 Comments

What does "=>" mean ? I'll try your solution soon.
=> means ES6 arrow function syntax. If you use node.js version< 4, use usual functions instead.
Thanks a lot! Works flawlessly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.