【发布时间】:2023-02-04 12:48:52
【问题描述】:
我需要在 MongoDB 中进行从日期到日期的查询。当没有 from 和 to 查询参数时,我的解决方案很好,但是当我在 URL 中写入时它崩溃了。
有什么问题,或者您对此有更好的解决方案。
错误
{"stringValue":""{ fromDate: '2022 年 12 月 31 日星期六' }"","kind":"string","value":{"fromDate":"2022 年 12 月 31 日星期六"},"path":" date","reason":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 })); });
【问题讨论】: