Вложенный запрос MongoDB в NodeJS

Я хочу выбрать из двух коллекций в MongoDB с NodeJS. Я выбираю из коллекции 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 ]

Что я путаю?


person Herbertusz    schedule 19.05.2016    source источник


Ответы (1)


Promise.all возвращает данные, переданные в функцию разрешения промиса. это должно работать

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){
        // ...
});
person pizzarob    schedule 19.05.2016