首页 > 解决方案 > 如何引用多个模型 mongoose mongodb

问题描述

我有 3 个模型 MonthlyMenu。FrozenFood 和 DailyDeal。

我正在创建一个订单模型,其中在 item 字段中我希望拥有来自上述模型之一的 item id。

如何引用猫鼬模式中的多个模型?

item: {
  type: mongoose.Schema.Types.ObjectId,
  required: true,
  ref: 'DailyDeal',
},

标签: node.jsmongodbmongoosemongoose-schema

解决方案


您可以为此使用 mongoose virtuals。order首先,通过执行以下操作为您的模式启用虚拟:

const order_schema = new mongoose.Schema({
...
  item: {
    type: mongoose.Schema.Types.ObjectId,
    required: true
  },
...
},
{
    toJSON: { virtuals: true }
});

然后像这样定义3个虚拟模式:

order_schema.virtual('frommonthlymenu', {
    ref: 'monthly_menu', // Your MonthlyMenu model name
    localField: 'item', // Your local field, like a `FOREIGN KEY` in RDS
    foreignField: '_id', // Your foreign field which `localField` links to. Like `REFERENCES` in RDS
    // If `justOne` is true, 'members' will be a single doc as opposed to
    // an array. `justOne` is false by default.
    justOne: true
});

order_schema.virtual('fromfrozenfood', {
    ref: 'frozen_food',
    localField: 'item',
    foreignField: '_id',
    justOne: true
});

//Third one here...

然后,您可以在查询集合时填充frommonthlymenufromfrozenfood路径。order

Lead.find(search_filter)
      .populate('frommonthlymenu')
      .populate('fromfrozenfood')
      .then(result => {
          //Whichever path is populated, that's how you know the collection "item" came from.
      })

推荐阅读