【发布时间】:2021-03-19 21:10:13
【问题描述】:
我有这个LikeSchema 用于Posts,我想要实现的是检查用户id 是否存在于这些喜欢文档的_user_id 数组中
假设我有这个Likes 文档数组
[
{
id: 'a',
_user_id: 'u1',
_post_id: 'p1'
},
{
id: 'b',
_user_id: 'u2',
_post_id: 'p1'
}
]
如何使用聚合检查用户 ID u1 是否存在于 likes 数组文档中?
我有这个 Like Schema
const LikeSchema = new Schema({
_post_id: {
type: Schema.Types.ObjectId,
ref: 'Post',
required: true
},
_user_id: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
})
还有我的聚合
const result = await Post.aggregate([
{
$match: { privacy: 'public' }
},
{
$lookup: {
from: 'likes',
localField: '_id',
foreignField: '_post_id',
as: 'likes'
}
},
{
$addFields: {
isLiked: {
$in: [req.user._id, '$likes'] // WONT WORK SINCE I STILL HAVE TO MAP AS ARRAY OF _user_id
}
}
}
])
我想到的解决方案是首先将数组映射为只有用户 ID 值,然后执行 $in 表达式。
如何在聚合阶段从lookup 映射likes 数组,以便它只包含用户ID 值的数组以使$in 表达式匹配?或者也许有更好的方法来检查对象数组中存在的值?
【问题讨论】:
标签: mongodb aggregation