javascript - 猫鼬填充不适用于 ID 数组
问题描述
我有这两个 3 模型用户、产品和订单,并且也相互引用。
我的订单架构:
const orderSchema = Schema({
buyerId:{
type: Schema.Types.ObjectId,
ref: 'User'
},
totalAmount: {
type: Number,
required: [true, "description is required"]
},
createdOn: {
type: Date,
default: new Date()
},
items:[{type:Schema.Types.ObjectId, ref: 'Product'}]})
我正在尝试像这样使用 populate() :
Order.find()
.populate('buyerId')//Reference to User Model
.populate('items')// Reference to Product Model
.exec(function (err, result){
console.log(result);// RETURNS ONLY buyerId populated
console.log(result.buyerId.name);//Successfully references to my User model and prints name
console.log(result.items);//Prints Undefined
})
您可以在上面看到我的控制台日志,它返回的只是填充的买家 ID(仅从我的用户模型中获得了参考)
好像我的 populate('items') 根本不起作用。items 字段包含 ID 数组,其中 ID 是产品的 ID。我需要同时参考用户和产品。我只是在关注猫鼬中的文档,我不知道我可能做错了什么。
解决方案
使用聚合
Order.aggregate([
{ $match:{ user:"sample_id"
}
},
{$lookup:{
from:'users', // users collection name
localField:'buyerId',
foreignField:'_id',
as:'buyerId'
}},
{
$lookup:{
from:'items', //items collection name
localField:'items',
foreignField:'_id',
as:'items'
}
},
])
推荐阅读
- c++ - 最长回文子串算法的时间复杂度
- mysql - 如何在 SSIS 中配置连接管理器以连接到远程服务器上的 MySQL 数据库?
- javascript - 基于jQuery中选择的先前表单隐藏选项
- javascript - Javascript按与数字的最短距离对数组进行排序
- r - R 中的 Bigrquery 库不上传数据并且不返回错误。按下停止时获取应用程序回调
- javascript - 为 Shopify 店面使用不同的搜索 API
- html - 如何在两行之间留出空间?
- reactjs - 验证DOMNesting(...):
- java - java 正则表达式 "^\\d{1,4}\\,(.*?),"
- python - IRIS 数据集 - 统计分析、平均值和模式