首页 > 解决方案 > 当 id 引用其他模型的子文档时如何填充 id

问题描述

我正在尝试填充引用不同模型的子文档的对象 id 数组,我还没有创建该子文档的模型。

这是示例

const UserSchema = new Schema({
    name: {
        type: String,
    },
    interests: [{ type: Schema.Types.ObjectId, ref: 'Interest' }],
}, {timestamps: true});

const Users = model('User', UserSchema);

const SubCategorySchema = new Schema({
    name: { type: String }
});


export const InterestSchema = new Schema({
    categoryName:  { type: String },
    subCategory:  [SubCategorySchema]
});

const Interests = model('Interest', InterestSchema);

兴趣文件

[
  {
    "_id": "60bffb7439ffa329c0904634",
    "categoryName": "",
    "subCategory": [
      {
        "_id": "60bffbd83d7f4e55a086c966",
        "name": "Hedge Fund"
      },
      {
        "_id": "60bffc163d7f4e55a086c967",
        "name": "Private Equity"
      },
      {
        "_id": "60bffc773d7f4e55a086c969",
        "name": "Venture Capital"
      }
    ]
  }
]

用户文件:

[{
  name: "test",
  interests: ["60bffc163d7f4e55a086c967"]
}]

所以现在interests数组我有子类别文档的对象ID,现在这就是我尝试过的

Users.find({}).populate({path: "Interest.subCategory"})

但它没有工作

标签: node.jsmongodbmongoose

解决方案


推荐阅读