繁体   English   中英

NodeJS中的嵌套MongoDB查询

[英]Nested MongoDB query in NodeJS

我想从带有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 ]

我搞砸了什么?

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){
        // ...
});

暂无
暂无

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

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