Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/43.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript NodeJS中的嵌套MongoDB查询_Javascript_Node.js_Mongodb_Es6 Promise - Fatal编程技术网

Javascript NodeJS中的嵌套MongoDB查询

Javascript NodeJS中的嵌套MongoDB查询,javascript,node.js,mongodb,es6-promise,Javascript,Node.js,Mongodb,Es6 Promise,我想用NodeJS从MongoDB中的两个集合中进行选择。我从chat_messages集合中选择,这里有一个userId属性,我想在ES6 Promise的帮助下用用户名扩展结果对象。我试过这个: 第一个console.log打印以下内容: [ { _id: 573b6f2af9172fd81252c520, userId: 2, ... }, { _id: 57388bd913371cfc13323bb

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

第一个console.log打印以下内容:

[
    {
        _id: 573b6f2af9172fd81252c520,
        userId: 2,
        ...
    },
    {
        _id: 57388bd913371cfc13323bbb,
        userId: 1,
        ...
    }
]
但第二个看起来像这样:

[ undefined, undefined ]

我搞砸了什么?

Promise。所有
返回传递到Promise的解析函数中的数据。这应该行得通

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