Mongoose 聚合 $match $get $lte 日期

问题描述 投票:0回答:1

如果请求带有 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
mongodb mongoose aggregate
1个回答
0
投票

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

}

© www.soinside.com 2019 - 2024. All rights reserved.