首页 > 解决方案 > 构建猫鼬模式时如何引用不同集合中的特定字段?

问题描述

我正在构建模式 (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);

标签: mongodbmongoosemongoose-schemamongoose-populate

解决方案


我认为,您可以通过使用来实现这一点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. 
});

MeatNameinmeatSchema可以是任何东西。


推荐阅读