【发布时间】:2020-01-11 07:35:00
【问题描述】:
我无法查询按日期过滤的集合
以下代码是我到目前为止的代码
//The following code shows how my schema is:
date: {type: Date, required: true}
//This is a date from a collection in MongoDB:
date: 2019-09-06T16:48:14.000+00:00
//This is how I saved the date in the MongoDB:
"2019/09/09 08:55:15"
//And this is how I perform the query in NodeJS:
let year = req.query.year;
let month = req.query.month;
let day = req.query.day;
let startDate = new Date(year, month, day);
let endDate = new Date(year, month, day);
// find documents in MongoDB
let query = SALES.find({ date: { $gte: startDate, $lte: endDate }});
// execute the query at a later time
query.exec(function (err, item) { // item is a dictionary
if (err) return handleError(err); // throws an error if any
if (item === null || item.length === 0) {
res.json({
status: 'empty',
});
}
else {
res.json({
salesRecord: item
});
}
});
我读到这很容易得到,但我做不到。欢迎任何帮助????
我的查询没有错误,只是我得到的响应是空的。 预期的结果是从指定日期获取日期
【问题讨论】:
-
你能出示你的
req.query吗? -
req.query 的值例如:年 = 2019、月 = 08、日 = 09 等
-
您的
startDate和endDate具有相同的值,因此您的数据库中的记录需要与new Date(year, month, day)具有完全相同的日期 -
是的,他们有,但查询不起作用;(
标签: javascript html node.js mongoose