简体   繁体   English

Node.js-猫鼬承诺-循环

[英]Node.js - mongoose promises - loop through

I am having a trouble with mongoose used with node.js. 我在与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). 在我的模型中,我只有组主管的ID,在这条路线中,我还想将supervisorName添加到变量(此名称存储在组模型中)。 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) (基本上,我只想遍历所有组,从mongodb获取其模型,并为每个组分配主管名称)

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

You can map your groups array into array of promises and use Promise.all to resolve them all. 您可以map您的组阵列到阵列promises ,并使用Promise.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. 猫鼬模型方法同时支持回调和Promise接口。 However to use the promise interface we need to use the exec method and remove the callbacks. 但是,要使用Promise接口,我们需要使用exec方法并删除回调。
  2. Promise.all takes an array of promises. Promise.all兑现了一系列承诺。 It waits for all of them to resolve and any of them to reject (give error). 它等待所有这些都解决,而所有这些都拒绝(给出错误)。 Note: The promises are executed in parallel 注意:Promise是并行执行的
  3. We have an array of group objects, we map them into promises. 我们有一个阵列group的对象,我们将它们映射到承诺。 Calling .findById and again using exec to get a promise from it. 调用.findById并再次使用exec从中获得承诺。 Note: Remember to return your promises 注意:记住要兑现您的承诺
  4. We update the object, and return it as the final result of promise. 我们更新对象,并将其作为promise的最终结果返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM