简体   繁体   中英

Filter documents from two collections in mongoDB using mongoose

I have two collections: "message" and "group_message_map". _id column of message collection I am storing in the group_message_map. Few of the group_message_map entry if I am deleting so, only the remaining common entry from both the collections I am trying to fetch but getting the response as empty. Here is my method:

getLimitedMessages(receiverId, senderId, page, size, callback) {
    var messages = [];
    GroupMessageMap.find({
            groupId: receiverId,
            userSId: senderId
        })
        .skip(parseInt(((size * page) - size)))
        .limit(parseInt(size))
        .sort({ $natural: -1 })
        .exec(function(err, maps) {
            if (err) {
                console.log('err is maps ', err);
            } else {
                maps.map((map) => {
                    Message.find({
                        _id: map.messageId
                    }, function(err, message) {
                        if (err) {
                            console.log('messages err ', err);
                        } else {
                            messages.push(message);
                        }
                    });
                });
            }
        });
    console.log('filtered messages: ' + messages);
};

Why not using $lookup or populate

maps.map((map) will not wait for async db call and before getting db response, you will get empty response

Refer these links

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ http://mongoosejs.com/docs/populate.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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