mongodb - 构建猫鼬模式时如何引用不同集合中的特定字段?
问题描述
我正在构建模式 (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);
解决方案
我认为,您可以通过使用来实现这一点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.
});
MeatName
inmeatSchema
可以是任何东西。
推荐阅读
- design-patterns - 使用 TypeState 模式时如何处理条件?
- python - Beautifulsoup 没有返回网页的完整 HTML
- c# - C#——计算字符串中单个数字(int)的出现次数——不使用 int 到 char 转换的变量
- sql - t-SQL 大于/小于一个值
- r - 提取部分字符串值,创建新的列名,并使数据框变宽
- python - 如何根据 Python 中 JSON 文件的语言名称返回文件扩展名?
- java - Android计步器,显示每天的步数
- kubernetes - Istio Ingress Gateway 在 Anthos 中不起作用
- google-apps-script - 如果表的大小为 13 个条目,则获取列表大小并检索它将占用多少个表的函数
- azure - Azure App Insights:如何限制特定域或 IP 地址的日志信息