【问题标题】: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);

【问题讨论】:

    标签: mongodb mongoose mongoose-schema mongoose-populate


    【解决方案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 可以是任何东西。

    【讨论】:

      猜你喜欢
      • 2016-01-27
      • 2015-04-11
      • 1970-01-01
      • 2016-05-17
      • 2020-03-27
      • 2016-07-15
      • 2016-02-17
      • 2021-09-12
      • 2016-02-07
      相关资源
      最近更新 更多