Mongoose aggregate $match $get $lte date

snvhrwxg  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(106)

如果请求带有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

字符串

qvtsj1bj

qvtsj1bj1#

尝试将日期设置为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
});

字符串
}

相关问题