【发布时间】:2020-01-03 21:15:48
【问题描述】:
我正在尝试查找用户是否喜欢产品,同时使用 $lookup 操作从集合中获取产品以搜索喜欢集合中的喜欢,其中包含两个字段 productId(likedProduct) 和 userID(who喜欢该产品)productId 和 userId 都是 ObjectId 类型 这是我的产品架构
const products = new mongoose.Schema({
created: {
type: Date,
default: Date.now()
},
images: [{
type: String
}]
});
并且喜欢架构
new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
index: true
},
productId: {
type: Schema.Types.ObjectId,
required: true,
index: true,
ref: 'products'
},
created: {
type: Date,
default: Date.now()
}
});
我尝试使用 $lookup 运算符作为
const { user } = req;
productsModels.aggregate([
{ $sort: { '_id': -1 } },
{ $limit: 10 },
{
$lookup: {
from: 'likes',
pipeline: [
{
$match: {
'productId': '$_id',
'userId':user.id
}
}
],
as: 'liked'
}
},
]);}
但即使用户喜欢该产品,它也没有给我预期的结果 我被喜欢为一个空数组!
{
created: "2019-08-30T10:46:53.692Z"
images: ["8f3447bb-8bb8-4c5a-acde-bcdc1b729c09"]
liked: []
price: 9
title: "developer"
userId: "5d68fea345353e1748cf7a10"
__v: 0
_id: "5d68fec745353e1748cf7a12"}
提前致谢
【问题讨论】:
-
另请参阅 Specify Multiple Join Conditions with
$lookup中的$lookup管道阶段文档。您基本上缺少$expr运算符,用于将product_id与父文档的_id进行比较。user.id部分可能没问题,只要它指向一个已经是ObjectId的值。