Szymek
Szymek

Reputation: 163

Node.js - mongoose promises - loop through

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

Answers (1)

Akshendra Pratap
Akshendra Pratap

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});
    });
});

Explanations:

  1. Mongoose Model methods supports both callbacks and promises interface. However to use the promise interface we need to use the exec method and remove the callbacks.
  2. 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 parallel
  3. We have an array of group objects, we map them into promises. Calling .findById and again using exec to get a promise from it. Note: Remember to return your promises
  4. We update the object, and return it as the final result of promise.

Upvotes: 2

Related Questions