首页 > 解决方案 > 仅当存在时才匹配 mongodb 查询的变量

问题描述

我正在使用聚合来返回符合特定条件的用户列表。问题是我从前端得到的变量并不总是设置好的。

所以我必须做这样的事情:

const match = {};

if (status) {
  match.status = status;
}

if (startDate && endDate) {
  match.createdAt = { $gte: startOfDay(startDate), $lte: endOfDay(endDate) };
}

await User.aggregate([
  {
     $match: match,
  },
]);

有没有办法直接在查询中编写它而不必match在聚合之外使用变量?

标签: mongodbmongoosemongodb-query

解决方案


您可以尝试以下方法:

    db.User.find(
            { $or: 
               [ { $and: [ { "status": { $exists: true } },{ "status": status } ] }, 
                 { $and: [ { "endDate": { $exists: true } },
                           { "startDate": { $exists: true } }, 
                           { $gte: startOfDay(startDate), $lte: endOfDay(endDate) }] } 
               ] })

推荐阅读