动态或查询为空,给出错误 - "$and/$or/$nor must be a nonempty array"



我希望查询具有或条件,如果该条件为空,则应返回空结果。但由于or查询为空,它返回一个错误'$and/$or/$nor must be a nonempty array'

我如何绕过这一点,注意如果或查询为空,我需要结果为空。

matchOrs是一个数组,它是$or查询,通常不是空的,但有时也会导致空数组,从而导致问题-'$and/$or/$nor must be a nonempty array'

const match = {
'$and': [{
'status': {
'$ne': 'rejected',
},
},
{
'raised_date': {
'$gt': start,
'$lte': end,
},
},
{
'$or': matchOrs,
},
{
'city': city,
}],
};

您可以在声明匹配后尝试创建$或对象,如果matchOr的长度大于0,则将其推送到$和数组:

const match = {
'$and': [{
'status': {
'$ne': 'rejected',
},
},
{
'raised_date': {
'$gt': start,
'$lte': end,
},
},
{
'city': city,
}],

};


if(matchOrs.length > 0){
match.$and.push({$or:matchOrs});
}

这将正常工作。但为了更好地练习,你应该使用括号符号:

if(matchOrs.length > 0){
match["$and"].push({$or:matchOrs});
}

相关内容

最新更新