【问题标题】:Nested MongoDB query in NodeJSNodeJS 中的嵌套 MongoDB 查询
【发布时间】:2016-05-20 04:32:44
【问题描述】:

我想使用 NodeJS 从 MongoDB 中的两个集合中进行选择。我从 chat_messages 集合中选择,有一个 userId 属性,我想在 ES6 Promise 的帮助下用用户名扩展结果对象。我试过这个:

db.collection("chat_messages")
    .find({"room" : roomName})
    .sort({"created" : 1})
    .toArray()
    .then(function(messages){
        console.log(messages);
        return Promise.all(messages.map(function(message){
            return db.collection("chat_users")
                .find({"id" : message.userId})
                .limit(1)
                .toArray()
                .then(function(users){
                    message.userName = users[0].name;
                });
        }));
    })
    .then(function(messages){
        console.log(messages);
    })
    .catch(function(error){
        // ...
    });

第一个 console.log 打印出这个:

[
    {
        _id: 573b6f2af9172fd81252c520,
        userId: 2,
        ...
    },
    {
        _id: 57388bd913371cfc13323bbb,
        userId: 1,
        ...
    }
]

但第二个看起来像这样:

[ undefined, undefined ]

我搞砸了什么?

【问题讨论】:

    标签: javascript node.js mongodb es6-promise


    【解决方案1】:

    Promise.all 返回传递给 promise 的 resolve 函数的数据。这应该工作

    db.collection("chat_messages")
        .find({"room" : roomName})
        .sort({"created" : 1})
        .toArray()
        .then(function(messages){
            let promises = [];
    
            messages.forEach(message => {
                promises.push(new Promise(resolve => {
                    db.collection("chat_users")
                        .find({"id" : message.userId})
                        .limit(1)
                        .toArray()
                        .then(function(users){
                            message.userName = users[0].name;
                            resolve(message);
                        });
                }));
            });
            return Promise.all(promises);
        })
        .then(function(messages){
            console.log(messages);
        })
        .catch(function(error){
            // ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-19
      • 2021-06-20
      • 1970-01-01
      • 2015-08-15
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      相关资源
      最近更新 更多