1

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});
});
});
1
  • One more information, supervisor is another group ;p Commented Jan 6, 2018 at 17:09

1 Answer 1

2

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

2 Comments

Woah, you made my day, can you explain why i need to do this that way? (Any comments on code or something please?)
Would you please add how to handle two operations? For example findById and counting how often this element is referenced in another collection, through OtherModel.countDocuments?

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.