简体   繁体   English

使用mongoose过滤mongoDB中两个集合中的文档

[英]Filter documents from two collections in mongoDB using mongoose

I have two collections: "message" and "group_message_map". 我有两个集合:“消息”和“ group_message_map”。 _id column of message collection I am storing in the group_message_map. 我存储在group_message_map中的消息集合的_id列。 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. 如果我要删除group_message_map条目,则很少,只有我试图获取的两个集合中剩余的公共条目,但响应为空。 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 为什么不使用$ lookup或填充

maps.map((map) will not wait for async db call and before getting db response, you will get empty response maps.map((map)将不等待异步数据库调用,并且在获得数据库响应之前,您将获得空响应

Refer these links 参考这些链接

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

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

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