简体   繁体   English

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

[英]Unable to fetch record from mongoDB as per date range using Node.js

I need to fetch records from mongoDB within the date range but as per my code no record is coming.我需要在日期范围内从 mongoDB 获取记录,但根据我的代码没有记录。 I am explaining my code below.我在下面解释我的代码。

ubot-stats:: ubot-stats::

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

The above is my collection and I need to fetch record as per created date.以上是我的收藏,我需要根据创建日期获取记录。

app.js::应用程序.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);
          }
        })

Here I need to fetch record as per created date within fromDate and toDate which is mention above but as per this code no recording is coming.在这里,我需要根据上面提到的fromDate and toDate中的创建日期获取记录,但根据此代码,没有记录即将到来。 Please help me to resolve this issue.请帮我解决这个问题。

With dates I recommend you ther the library moment .有了日期,我向您推荐图书馆的时刻 I always use it to use dates.我总是用它来使用日期。

Then you could try this filter:然后你可以试试这个过滤器:

const startDate = moment(req.body.fromDate)
const endDate = moment(req.body.toDate)

{ '$and': [
   { 'created_date': { '$gte': startDate} }, 
   { 'created_date': { '$lte': endDate} }
]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM