【问题标题】:mongodb $match operation in $lookup to compare objectId's not working as expected [duplicate]$lookup 中的 mongodb $match 操作以比较 objectId 没有按预期工作 [重复]
【发布时间】: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 的值。

标签: node.js mongodb


【解决方案1】:

试试这个

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) 将 userid 转换为 mongo 对象 id 所以我们使用mongoose.Types.ObjectId

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 2018-04-16
    • 1970-01-01
    • 2018-01-21
    • 2020-05-31
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    相关资源
    最近更新 更多