[英]MongoDB aggregation and $lookup always returning empty array
Been struggling with this for a while can't work out why I am always getting an empty array for my loop up data.已经为此苦苦挣扎了一段时间无法弄清楚为什么我总是为我的循环数据获取一个空数组。
I have data in my 'users' collection我的“用户”集合中有数据
{
storeid: 1,
name: 'joe bloggs'
}
I have a stores collection with the following data in我有一个商店集合,其中包含以下数据
{
_id: ObjectId(1),
storeName: 'Store name'
}
I want to pull the storename that each user is part of when getting all users.我想在获取所有用户时提取每个用户所属的商店名称。 I have a query like the below to do this:我有一个像下面这样的查询来做到这一点:
User.aggregate([
{
$lookup: {
from: "store",
localField: "storeid",
foreignField: "_id",
as: "storeDetail"
}
}
])
.then(users => {
res.send(users);
}).catch(err => {
//error
});
However what I get here is 'storeDetail' always returning blank.但是,我在这里得到的是 'storeDetail' 总是返回空白。 Not too sure what I am doing wrong, I have checked that my collection names are correct as per db.getCollectionNames() from the mongo shell.不太确定我做错了什么,我已经根据 mongo shell 中的 db.getCollectionNames() 检查了我的集合名称是否正确。
Thanks,谢谢,
Turns out I was trying to use different Schema types in localField (string) and foreignField (ObjectId).原来我试图在 localField (string) 和 foreignField (ObjectId) 中使用不同的模式类型。 Converting the localField in the model to be of type ObjectId fixed it.将模型中的 localField 转换为 ObjectId 类型修复了它。
type: String,//Didn't work
type: mongoose.Schema.Types.ObjectId,//Did work
Note: You mentioned wrong schema注意:您提到了错误的架构
{
_id: ObjectId(1),
storeName: 'Store name'
}
Here is the solution这是解决方案
ObjectId(1) is wrong. ObjectId(1) 是错误的。 ObjectId always be the hash value of 24 lengths of string. ObjectId 始终是 24 个长度的字符串的哈希值。
User Collection:用户收藏:
{
"_id" : ObjectId("5b8d246730739cd950b7b314"),
"storeid" : ObjectId("5b8d249b30739cd950b7b323"),
"name" : "joe bloggs"
}
Store Collection店铺收藏
{
"_id" : ObjectId("5b8d249b30739cd950b7b323"),
"storeName" : "Store name"
}
Mongo Query蒙戈查询
db.getCollection('user').aggregate([
{$lookup:{from: 'store',localField: 'storeid',foreignField: '_id',as: 'stores'}},
])
Result结果
{
"_id" : ObjectId("5b8d246730739cd950b7b314"),
"storeid" : ObjectId("5b8d249b30739cd950b7b323"),
"name" : "joe bloggs",
"stores" : [
{
"_id" : ObjectId("5b8d249b30739cd950b7b323"),
"storeName" : "Store name"
}
]
}
Hope it helps you.希望对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.