有条件参数的猫鼬聚合

时间:2019-05-27 08:46:07

标签: node.js mongoose

我有用于猫鼬的工作汇总代码

    const AccountProduct = await AccountProductModel.aggregate([
            {
                $match: { userID: userID }
            },
            {
                $addFields: {
                    taggedProducts: {
                        $filter: {
                            input: "$taggedProducts",
                            cond: {
                                 $and: {
                                    $eq: [ "$$this.isChecked", true ],
                                    $eq: [ "$$this.walletID", walletID]
                                 }
                            }
                        }
                    }
                }
            }
        ])

它确实返回了所需的数据,但是如果没有提供walletID,我希望有一个条件,那么条件应该看起来像这样

                        cond: {
                             $and: {
                                $eq: [ "$$this.isChecked", true ]
                             }
                        }

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在查询之前将条件提取到变量中。

let myCond = [{$eq: [ "$$this.isChecked", true ]}];

if (walletID) myCond.push({$eq: [ "$$this.walletID", walletID]});

然后

cond: {$and: myCond}