我正在为我的公司创建一个Rest API进行报告 路由传递日期以查找2个给定日期中的数据
router.get('/smDcr/:currentDate?&:lastDate:', authorize, getDcrBetweenDates);
控制器操作以获取日期之间的数据
exports.getDcrBetweenDates = async(req, res, next) => {
try{
const lastDate = req.params.lastDate;
const currentDate = req.params.currentDate;
console.log(lastDate);
const dcr = await Dcr.find({
where: {
createdAt: {
$between:[currentDate, lastDate]
}
}
});
if(!dcr) return res.status(400).json({message: "No DCR found between mentioned Dates!!"});
return res.status(200).json({ dcr});
}catch(ex){
next(ex)
}
}
在邮递员中传递参数时,我得到的所有报告都不特定于参数中给出的日期 http://localhost:3000/smDcr/?currentDate=2019/09/11&?lastDate=2019/09/11
答案 0 :(得分:0)
您不需要使用$ where条件,只需在find函数中设置请求对象即可
我认为您应该使用$ gte和$ lte运算符,而不要使用$ between(cf @ponzao answer)
这里是一个例子:
const dcr = await Dcr.find({
"createdAt": {
"$gte": new Date(currentDate),
"$lt": new Date(lastDate)
}
});
编辑:
如果仍然无法使用,则可能是因为您的日期未格式化,也许您应该使用日期库,例如moment,然后尝试这样操作:
const moment = require('moment');
const dcr = await Dcr.find({
"createdAt": {
"$gte": new Date(moment(currentDate, 'YYYY/MM/DD').format()),
"$lt": new Date(moment(lastDate, 'YYYY/MM/DD').format())
}
});
希望有帮助。
答案 1 :(得分:0)
如果您使用查询字符串代替查询参数来获取至少日期会更好。在您提供的路线中:
router.get('/smDcr/:currentDate?&:lastDate:', authorize, getDcrBetweenDates);
由于(?),使用url中的?&:传递第二个日期值将被解释为查询字符串。 您正在通过调用此端点来访问此端点:
http://localhost:3000/smDcr/?currentDate=2019/09/11&?lastDate=2019/09/11
在这种情况下, currentDate 将被视为查询字符串,与 lastDate
相同所以我建议您改用这个:
router.get('/smDcr', authorize, getDcrBetweenDates);
然后在您的控制器中,访问以下值:
const lastDate = req.query.lastDate;
const currentDate = req.query.currentDate;
要访问它,您应该致电:
http://localhost:3000/smDcr?currentDate=2019/09/11&lastDate=2019/09/11
这是路由的官方文档。 Express Routing