我正在尝试在用户使用$ lookup操作从集合中获取产品时查找用户是否喜欢该产品,以查找likes集合中的like,该字段由两个字段productId(likedProduct)和userID(who喜欢该产品)productId和userId均为ObjectId类型 这是我的产品架构
const products = new mongoose.Schema({
created: {
type: Date,
default: Date.now()
},
images: [{
type: String
}]
});
并且喜欢Schema
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"}
预先感谢
答案 0 :(得分:0)
尝试
const { user } = req;
productsModels.aggregate([
{ $sort: { '_id': -1 } },
{ $limit: 10 },
{
$lookup: {
from: 'likes',
let: {productId:"$_id"},
pipeline: [
{
$match: {
$expr:{$eq:['$_id', '$$productId']}},
'userId': mongoose.Type.Object(user.id)
}
}
],
as: 'liked'
}
},
]);}
您的查询中缺少两件事
1)将用户ID转换为mongo对象ID,因此我们使用了mongoose.Types.ObjectId
2)您不能在内部管道中直接使用外部集合字段,因为您已经创建了temp变量,因此我们使用let
进行声明并与内部字段匹配,我们需要使用$expr
< / p>