无法使用Node.js根据日期范围从mongoDB中获取记录



我需要从mongoDB中提取日期范围内的记录,但根据我的代码,没有记录。我在下面解释我的代码。

ubot统计::

{
"_id" : ObjectId("60aa4ac8dbf65f620fd61c35"),
"cec" : "subhrajp",
"action" : "Admin",
"created_date" : ISODate("2021-05-31T06:52:56.000Z"),
"count" : 12
}

以上是我的收藏,我需要根据创建日期获取记录。

app.js::

const filter = {'$gte': new Date(req.body.fromDate).toISOString(), '$lte': new Date(req.body.toDate).toISOString()};
console.log('filter', filter);//{'$gte': '2021-05-27T00:00:00.000Z','$lte': '2021-05-31T00:00:00.000Z'}
connObj.collection("ubot-stats").find({created_date:filter}).toArray(function(error, docs) {
console.log('nError =>', error);
console.log('nDocs =>', docs);
if (error || !docs) {
responseObj = {
status: 'error',
msg: `Error occurred while fetching docs from "stats" collection present in ${dbName} database`,
body: error
};
client.close();
res.send(responseObj);
}else{
responseObj = {
status: 'success',
msg: `successfully fetched the docs`,
body: docs
};
client.close();
res.send(responseObj);
}
})

在这里,我需要根据上面提到的fromDate and toDate中的创建日期获取记录,但根据此代码,没有记录。请帮我解决这个问题。

有了日期,我建议你去图书馆。我总是用它来表示日期。

然后你可以试试这个过滤器:

const startDate = moment(req.body.fromDate)
const endDate = moment(req.body.toDate)
{ '$and': [
{ 'created_date': { '$gte': startDate} }, 
{ 'created_date': { '$lte': endDate} }
]}

最新更新