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!