我有用于猫鼬的工作汇总代码
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 ]
}
}
我该怎么做?
答案 0 :(得分:1)
您可以在查询之前将条件提取到变量中。
let myCond = [{$eq: [ "$$this.isChecked", true ]}];
if (walletID) myCond.push({$eq: [ "$$this.walletID", walletID]});
然后
cond: {$and: myCond}