【问题标题】:Filter documents from two collections in mongoDB using mongoose使用 mongoose 从 mongoDB 中的两个集合中过滤文档
【发布时间】:2018-09-29 16:57:06
【问题描述】:

我有两个集合:“message”和“group_message_map”。我存储在 group_message_map 中的消息集合的 _id 列。如果我要删除一些 group_message_map 条目,则只有我试图获取的两个集合中剩余的公共条目,但响应为空。这是我的方法:

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);
};

【问题讨论】:

  • 会映射等待异步数据库调用吗?
  • 不是,所以我得到的是空数组。我也尝试使用 async 和 await 但收到此错误:“ReferenceError:regeneratorRuntime 未定义”。我也安装了所有相关的依赖项和 devDependencies。

标签: node.js mongodb mongoose


【解决方案1】:

为什么不使用 $lookup 或填充

ma​​ps.map((地图) 不会等待异步数据库调用,在获得数据库响应之前,您将得到空响应

参考这些链接

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

【讨论】:

  • populate 我试过但没用。让我也试试 $lookup。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2020-01-31
  • 2018-01-26
相关资源
最近更新 更多