Below is the code I am having issues with:
const users = []
event.registeredUsers.forEach(userId => {
User.findOne({ _id: userId }).then(user => {
console.log(user) // logs a valid user
users.push(user)
});
});
console.log(users) // logs empty array
The event is a MongoDB document that has registeredUsers field which is an array of MongoDB object Ids. When console logging the user returned in the then block it does shows a valid user document but when res.send(users) after the loop has been finished, it shows empty array in the browser.
You are trying to execute promise based code inside forEach which doesnt work the way you expect it work. Use either for..of
or Promise.all
for..of
(sequential)
const users = []
for(const userId of event.registeredUsers) {
User.findOne({ _id: userId }).then(user => {
console.log(user) // logs a valid user
users.push(user)
});
}
console.log(users)
Promise.all
(in parallel)
Promise.all(event.registeredUsers.map(userId => {
return User.findOne({ _id: userId }).then(user => {
console.log(user) // logs a valid user
return user;
});
}).then(users => console.log(users));