如果请求带有 startDate endDate 查询,我会尝试匹配日期。但是,我使用以下方法返回空数据。
try {
console.log(req.query.startDate);
console.log(new Date(req.query.startDate));
console.log(new Date(req.query.startDate).toISOString());
let match = {};
if (req.query.userId) {
match.userId = req.query.userId;
}
if (req.query.startDate && req.query.endDate) {
match.createdAt = {
$gte: new Date(req.query.startDate),
$lt: new Date(req.query.endDate)
};
}
const docs = await Sale.aggregate([{
$match: match
}
]);
return res.status(200).json({
docs
});
}
From console log:
2019-01-01
2019-01-01T00:00:00.000Z
2019-01-01T00:00:00.000Z
尝试将日期设为 ISO 字符串
try {
console.log(req.query.startDate);
console.log(new Date(req.query.startDate));
console.log(new Date(req.query.startDate).toISOString());
let match = {};
if (req.query.userId) {
match.userId = req.query.userId;
}
if (req.query.startDate && req.query.endDate) {
match.createdAt = {
$gte: req.query.startDate.toISOString(),
$lt: req.query.endDate.toISOString()
};
}
const docs = await Sale.aggregate([{
$match: match
}
]);
return res.status(200).json({
docs
});
}