【问题标题】:Conditional $or in MongoDBMongoDB 中的条件 $or
【发布时间】:2023-02-04 12:48:52
【问题描述】:

我需要在 MongoDB 中进行从日期到日期的查询。当没有 from 和 to 查询参数时,我的解决方案很好,但是当我在 URL 中写入时它崩溃了。

有什么问题,或者您对此有更好的解决方案。

错误

{"stringValue":""{ fromDate: '2022 年 12 月 31 日星期六' }"","kind":"string","value":{"fromDate":"2022 年 12 月 31 日星期六"},"path":" date","re​​ason":null,"valueType":"Object","statusCode":400}

路线

router.get("/:_id/logs", (req, res) => {
  const fromDate = new Date(req.query.from).toDateString();
  const toDate = new Date(req.query.to).toDateString();
  User.findById(req.params._id)
    .then((user) => {
      Exercise.find({
        $and: [
          { user: req.params._id },
          fromDate !== "Invalid Date"
          ? { date: { $gte: { fromDate } } }
          : {},
          toDate !== "Invalid Date" ? { date: { $lte: { toDate } } } : {},
        ],
      })
        .limit(+req.query.limit)
        .sort({ date: 1 })
        .exec()
        .then((exercises) =>
          res.json({
            username: user.username,
            userId: user._id,
            count: exercises.length,
            logs: exercises,
          })
        )
        .catch((err) => res.json({ ...err, statusCode: 400 }));
    })
    .catch((err) => res.json({ ...err, statusCode: 400 }));
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在这种情况下,首先构建查询运算符会更简单:

    const fromDate = new Date(req.query.from).toDateString();
    const toDate = new Date(req.query.to).toDateString();
    
    const dateOperator = {};
    if (fromDate !== "Invalid Date") {
      dateOperator.$gte = fromDate;
    }
    if (toDate !== "Invalid Date") {
      dateOperator.$lte = toDate;
    }
    
    Exercise.find({
            $and: [
              { user: req.params._id },
              { date: dateOperator },
            ],
          })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 2011-08-26
      相关资源
      最近更新 更多