【问题标题】:Mongoose - populate object that contains other fieldsMongoose - 填充包含其他字段的对象
【发布时间】:2018-12-21 18:48:33
【问题描述】:

我有一个对象数组。我想保存集合中的某些部分,并引用第二个集合来检索补充数据

集合 1

statute: [{
    _id: { type: ObjectId, ref: "Statute" },
    subsection: [{
      header: String,
    }],
}],

使用 .populate("statute._id", "title statute") 我希望得到以下输出:

"statute": [
    {
        "subsection": [],
        "_id": "5c15bcf348549e2aac5e99d3",
        "title": 13,
        "statute": 103
    },
 ]

但我收到的输出是

"statute": [
        {
            "subsection": [],
            "_id": {
                "_id": "5c15bcf348549e2aac5e99d3",
                "title": 13,
                "statute": 103
            }
        },

如何告诉 Mongoose 根据 statute._id 进行填充,但返回 statute 中的值?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    据我所知,这是不可能的,因为这意味着在模式中添加/覆盖字段,这使得猫鼬在您点击 .save() 时无法知道如何处理这些字段在这样创建的对象上。

    但是,除非您需要一个实际的 mongoose 对象,否则您可以将聚合函数与一些查找 + 投影魔术一起使用,就像这样(不过,您可能必须适应您的 doc 结构):

    statute.aggregate([
     { $match : {}},
     { $unwind: '$statute'} // splitting the array into separate fields
     {
       $lookup: // see https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
         {
           from: 'Statute',
           localField: '_id',
           foreignField: '_id,
           as: 'remote_statute'
         }
     },
     {
       $project: {
        "subsection": '$subsection',
        "_id": "$remote_statute._id",
        "title": '$remote_statute.title',
        "statute": '$remote_statute.statute'
       }
     }
    ])
    

    注意:您可能必须添加一个分组阶段才能将结果重新合并到一个数组中。如果您不知道法规的确切字段是什么样的,您还可以查看要应用于填充法规的 $replaceRoot 函数,但我觉得这不适合您的用例。

    另外,我建议您将 _id 字段重命名为更具描述性的名称,例如 statuteId,否则这可能会干扰 mongoose 设置的 _id 字段。

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 2013-05-14
      • 2023-04-01
      • 2013-03-23
      • 2012-01-22
      • 2017-05-21
      • 2019-06-23
      • 2020-06-26
      • 2016-02-20
      相关资源
      最近更新 更多