簡體   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