【问题标题】:How to use $lookup in mongodb to get data from this table that joins with another table如何在 mongodb 中使用 $lookup 从该表中获取与另一个表连接的数据
【发布时间】:2019-11-21 12:31:34
【问题描述】:

我有以下两种方案:

方案贴:

让架构 = {

id:“帖子”,

属性:{

内容:{类型:“字符串”,默认:''},

作者:{

类型:“对象”,

id: { type: "object" },

头像:{类型:“字符串”},

名字:{类型:“字符串”},

姓氏:{类型:“字符串”},

状态:{类型:“字符串”}

},

标签:{ type: 'string' },

类别:{

类型:“对象”,

id: { type: "object" },

名称:{类型:“字符串”}

},

图片:{

类型:“数组”,

项目:{

类型:“对象”,

属性:{

filePath: { type: "string" },

排序:{类型:'字符串'},

}

}

},

};


方案报告:

让架构 = {

id:“报告”,

属性:{

记者:{

类型:“对象”,

userId: { type: "object" },

名字:{类型:“字符串”},

姓氏:{类型:“字符串”},

状态:{类型:“字符串”}

},

到:{

类型:“对象”,

id: { type: "object", ref: 'post' },

类型对象:{类型:“字符串”}

},

reportType: { type: "string" }, //SPAM||FAKE ..

内容:{类型:“字符串”}

}

enter image description here

如何使用 $lookup 或 $populate 从表中获取数据 post 以便: post._id = report.to.id 我这样写它按要求返回错误:

findPromise = model.aggregate([

    { $lookup:{from:"reports",localField:"_id", foreignField:"to.id", as:"res"}},
    {
      $match: query,
    },
    { $skip: skip },
    { $limit: pageSize * 1 },

  ])

请帮帮我, 谢谢大家。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    您的查询是正确的,只要确保外部和本地字段的 typeof 相同即可。

    【讨论】:

    • localField:"_id": ObjectId, foreignField:"to.id": + to: Object, + id: ObjectId 我还是没有返回正确的结果
    • 您能否提供两个集合中的至少一个样本记录,以便我进一步开展工作
    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 2020-12-17
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多