【问题标题】:MongooseJS - How to specify a field of an object in an array of a document in Mongoose Populate Virtuals?MongooseJS - 如何在 Mongoose Populate Virtuals 的文档数组中指定对象的字段?
【发布时间】:2018-06-05 00:56:56
【问题描述】:

假设我有以下文件

{
  name: "Johnny Doe",
  age: "55",
  organizations: [
  {name: "Org A",
   members: 22
  },
  {name: "Org B",
   members: 25
  }]
}

假设我有另一个架构的虚拟设置

SomeSchema.virtual('organizations'){
 ref:"Person", //the collection to reference
 localField:"organization_name",  //the field in this Schema
 foreignField: [???]  //I want to access Person.organizations[].name
}

如何在 localField/foreignField 中指定我想要的字段?我已经尝试过像 MongoDB 中一样的“organizations.$.name”,但它不起作用,它返回一个空数组。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我找到了答案。只需使用field_array.field_of_array_object 或在我的示例中使用organizations.name。是否在数组中无关紧要,只需使用 . 表示法即可。

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2017-11-17
      • 1970-01-01
      • 2020-03-23
      • 2016-12-09
      • 2023-01-17
      • 2014-03-24
      • 2020-12-09
      • 2021-10-06
      相关资源
      最近更新 更多