node.js - 如何引用多个模型 mongoose mongodb
问题描述
我有 3 个模型 MonthlyMenu。FrozenFood 和 DailyDeal。
我正在创建一个订单模型,其中在 item 字段中我希望拥有来自上述模型之一的 item id。
如何引用猫鼬模式中的多个模型?
item: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'DailyDeal',
},
解决方案
您可以为此使用 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...
然后,您可以在查询集合时填充frommonthlymenu
或fromfrozenfood
路径。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.
})
推荐阅读
- c++ - .h.in 文件未找到
- java - Amazon Forecast 查询 Java 集成
- instruments - 当我远程使用 R&S 网络分析仪时,我无法通过“打印到文件”来存储文件?
- javascript - 上传不同md5的文件,最后过期
- node.js - AWS Beanstalk - 在工作人员和网络服务器之间共享数据库层
- string - 为什么 jq --raw-output 参数无法从 @csv 输出中删除引号?
- android - 使用微调器选择值进行 Firebase 查询
- graphics - 双击窗口的标题栏和单击窗口的最大化按钮有什么区别吗?
- r - 传播具有重复列的 data.frame
- java - 如何创建多个前台通知?