1

I am trying to create an api to get the data between two dates in NodeJS. My database is mongoDB, my data looks like this

_id:ObjectId("60ff19125474fa0ec45c2d1a")
username:"abc"
Date:"2021-7-26"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

_id:ObjectId("6101f4a4676d8b2b743a2d58")
username:"abc"
Date:"2021-7-27"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

_id:ObjectId("6102e1357ad1ed20d4642db0")
username:"abc"
Date:"2021-7-28"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

_id:ObjectId("6104717cb025c025e8b2d15e")
username:"abc"
Date:"2021-8-01"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

i want to fetch the data between two dates, i create an api to fetch data by date (single), need some modification to fetch it between two dates.

here is api to fetch data by date:


fetchHistorybydate =(req,res)=>{
  
  var HistoryList = []
      User.find({"username":req.body.username, "leave":{ $exists : false} },function(err,data){              
        for(var i =1 ;i<data.length;i++){
          var NDate = data[i].Date;
          if(NDate==req.body.date){
            HistoryList.push(data[i])
          }
        }
        if(err)
        {res.status(300).json("Error")}
          else{
          var token = jwt.sign({
            data: 'foobar'
          }, 'secret', { expiresIn: "30 minute"})
          res.status(200).json({AccessToken: token,data:HistoryList})
    }
  })
}


for example:

let say there are two calender on frontend one is for Fromdate and second is for Todate, if user select date from Fromdate calender this 2021-7-26 and from Todate calender this 2021-7-28 then it will only fetch the records from these dates.

the output should be, according to above data

_id:ObjectId("60ff19125474fa0ec45c2d1a")
username:"abc"
Date:"2021-7-26"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

_id:ObjectId("6101f4a4676d8b2b743a2d58")
username:"abc"
Date:"2021-7-27"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

_id:ObjectId("6102e1357ad1ed20d4642db0")
username:"abc"
Date:"2021-7-28"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"

Please help me how to do this.

TimeToCode
  • 1,458
  • 3
  • 18
  • 60

1 Answers1

3

You have to update the store Date object in the Date parameter of your database. After that, you'll be able to query by two date ranges. Currently, your Date parameter is a string, but, you have to convert it to a Date object.

Here is the solution after converting into Date object:

fetchHistorybydate = (req, res) => {
    var query = {
        username: req.body.username,
        Date: {
            $gte: new Date(req.body.Fromdate).toISOString(),
            $lte: new Date(req.body.Todate).toISOString()
        },
        leave: { $exists: false }
    }

    User.find(query, function (err, data) {
        if (err) { return res.status(300).json("Error") }
        else {
            return res.status(200).json({ data: data })
        }
    })
}

Note: No need to loop through the entire array again after retrieving the data. Because we already query from our database with the $gte and $lte parameters. Where $gte means greater than or equal and $lte means less than or equal.

You can also use $gt (greater than) and $lt (less than).

Shariful Islam Mubin
  • 2,146
  • 14
  • 23
  • i got this error RangeError: Invalid time value at this line ```$gte: new Date(req.body.Fromdate).toISOString(),``` – TimeToCode Aug 06 '21 at 11:22
  • but when do it like this ```$gte:"2021-07-26"``` and ```$lte:"2021-07-30"``` i got data but excluding 26th date data it gets data from 28 – TimeToCode Aug 06 '21 at 11:23
  • i don't want to hard this, i will be passing the values from calender on frontend, please helpppp! – TimeToCode Aug 06 '21 at 11:24
  • Just updated my answer, have a look, and let me know if it works or not. – Shariful Islam Mubin Aug 06 '21 at 11:29
  • i tried that way too, and got empty data, output: ```"data":[]``` – TimeToCode Aug 06 '21 at 11:31
  • 1
    **UPDATED ANSWER:** You have to update the store Date object in the Date parameter of your database. After that, you'll be able to query by two date ranges. Currently, your Date parameter is a string, but, you have to convert it to a Date object. – Shariful Islam Mubin Aug 06 '21 at 11:34
  • but could u please tell me how to store the date into this format ```2021-08-04``` when i udpate the datatype of date it stores the date like this ```2021-08-04T00:00:00.000Z``` – TimeToCode Aug 06 '21 at 11:46
  • Yeah, because the Date object also has a time in it. And, by default, the time is **12:00 AM**. That's why it's adding `00:00:00` which is basically 12:00 AM in 24 hours format. – Shariful Islam Mubin Aug 06 '21 at 11:47
  • but i don't want time with date, it will create problem for me when i will be fetching date on frontend from api, can we insert it without time? – TimeToCode Aug 06 '21 at 11:49
  • Actually, it will not cause any issues. Because we're converting your front-end Date string to object with this line of code: `$gte: new Date(req.body.Fromdate).toISOString(),` and, it take cares the rest. – Shariful Islam Mubin Aug 06 '21 at 11:51
  • but i was fetching the date on other screen too, for some other purpose and it is causing problem, i just checked that, please help how to store it only date – TimeToCode Aug 06 '21 at 11:56
  • you can convert the Date object to a string. You can read here: https://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object – Shariful Islam Mubin Aug 06 '21 at 11:58