如何引用多个模型 mongoose mongodb
How to ref to multiple models mongoose mongodb
我有 3 个模型的 MonthlyMenu。 FrozenFood 和 DailyDeal。
我正在创建一个订单模型,在项目字段内我想拥有来自上述模型之一的项目 ID。
如何在猫鼬模式中引用多个模型?
item: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'DailyDeal',
},
您可以为此使用 mongoose 虚拟机。首先,通过执行以下操作为您的 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...
然后您可以在查询 order
集合时填充 frommonthlymenu
或 fromfrozenfood
路径。
Lead.find(search_filter)
.populate('frommonthlymenu')
.populate('fromfrozenfood')
.then(result => {
//Whichever path is populated, that's how you know the collection "item" came from.
})
我有 3 个模型的 MonthlyMenu。 FrozenFood 和 DailyDeal。
我正在创建一个订单模型,在项目字段内我想拥有来自上述模型之一的项目 ID。
如何在猫鼬模式中引用多个模型?
item: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'DailyDeal',
},
您可以为此使用 mongoose 虚拟机。首先,通过执行以下操作为您的 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...
然后您可以在查询 order
集合时填充 frommonthlymenu
或 fromfrozenfood
路径。
Lead.find(search_filter)
.populate('frommonthlymenu')
.populate('fromfrozenfood')
.then(result => {
//Whichever path is populated, that's how you know the collection "item" came from.
})