构建猫鼬模式时如何引用不同集合中的特定字段?

Posted

技术标签:

【中文标题】构建猫鼬模式时如何引用不同集合中的特定字段?【英文标题】:How to reference a specific field from different collection when building a mongoose schema? 【发布时间】:2021-12-12 11:08:54 【问题描述】:

我正在构建模式 (Meal),我希望从不同模式 (Meat) 的不同字段 (meatName) 中获取此模式中的字段 (meat_name) 之一。 我知道填充方法,但它引用整个集合,我想引用特定字段。

    -Meat Schema-
    const meatSchema= new Schema(
  MeatName: String,
  MeatDescription: String,
);
module.exports = mongoose.model("Meat", meatSchema);

    -Meal Schema-
    const mealSchema= new Schema(
  mealName: String,
  mealPrice: Number,
  meat_name: 
    type: Schema.Types.ObjectId,
    ref: "Meat" /*populate method return the entire collection, but I want just the meatName field in that collection */,
  ,
);
module.exports = mongoose.model("Meal", mealSchema);

【问题讨论】:

【参考方案1】:

我认为,您可以通过使用 virtual 来实现这一点(在此处阅读更多信息 https://mongoosejs.com/docs/tutorials/virtuals.html

根据您的问题-

mealSchema.virtual('meat_name', 
  ref: 'Meat', // ref model to use
  localField: 'meat_name', // field in mealSchema
  foreignField: 'MeatName', // The field in meatSchema. 
);

meatSchema 中的MeatName 可以是任何东西。

【讨论】:

以上是关于构建猫鼬模式时如何引用不同集合中的特定字段?的主要内容,如果未能解决你的问题,请参考以下文章