Reputation: 163
I am having a trouble with mongoose used with node.js. In my model I am having only group supervisor's ID, and in this route I want also to add supervisorName to variable (this name is stored in Group model). So, yeah, I've read some about promises, but still, I dont have any idea how to solve that. (Basically, I just want to loop through all groups, get their models from mongodb, and assign supervisor name to every group)
router.get('/manage', function(req, res, next) {
Group.find({}, function(err, groups) {
groups.forEach(function(group) {
Group.findById(group.supervisor, function(err, supervisor) {
group.supervisorName = supervisor.name;
console.log(supervisor.name);
});
});
}).then(function() {
res.render('groups/groups_manage', {groups : groups});
});
});
Upvotes: 1
Views: 975
Reputation: 2040
You can map
your groups array into array of promises
and use Promise.all
to resolve them all.
router.get('/manage', function(req, res, next) {
Group.find({})
.exec() // 1
.then(groups => {
return Promise.all(groups.map(group => { // 2, 3
return Group.findById(group.supervisor)
.exec()
.then((supervisor) => { // 4
group.supervisorName = supervisor.name;
return group;
});
}));
})
.then(propGroups => {
res.render('groups/groups_manage', {groups : popGroups});
});
});
exec
method and remove the callbacks.Promise.all
takes an array of promises. It waits for all of them to resolve and any of them to reject (give error). Note: The promises are executed in parallelgroup
objects, we map them into promises. Calling .findById
and again using exec
to get a promise from it. Note: Remember to return your promisesUpvotes: 2