且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mongodb $lookup 中的 $match 操作来比较 objectId 没有按预期工作

更新时间:2022-06-08 22:11:13

试试这个

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'
                }
            },
        ]);}

在您的查询中缺少两件事

In your query two things where missing

1) 将 userid 转换为 mongo 对象 id 所以我们使用了 mongoose.Types.ObjectId

1) Converting userid to mongo object id so we used mongoose.Types.ObjectId

2) 您不能在内部管道中直接使用外部集合字段,为此您创建了临时变量,因此我们使用 let 声明并与内部字段匹配,我们需要使用 $expr

2) You can't use outer collection field directly in inner pipeline for this you have create temp variable so we used let to declare and to match with internal field we need to use $expr