ExpressJS: Mongoose query on ISO DATE based on todays date yyyy-mm-dd


I have date something like this

"createdAt": "ISODate('2021-07-07T06:41:46.000Z')"

I have written below mongoose query to fetch records for today. But below query fetched empty.

let meeting = await Meeting.find({
     createdAt :  {$lt: new Date().toISOString(),$gte: new Date().toISOString()}

I have tried below one more way with static date, it worked. I want to fetch data on dynamic todays date.

let meeting = await Meeting.find({ 
  createdAt : {
  '$eq': new Date('2021-07-07T06:41:46.000Z')

Can someone help me on this


I’m assuming the type of "createdAt" field is Date in Mongoose schema (you should convert to Date if it wasn’t the case).


When you want to filter documents on a specific day, you can use the condition:

0:00 the day <= createdAt < 0:00 the following day

For example, to filter meetings on 07/07/2021, the condition will be:

0:00 07/07/2021 <= createdAt < 0:00 08/07/2021


With that logic in mind, the code is pretty straightforward:

let today = new Date();
today.setHours(0,0,0,0); // set to 0:00

let tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)

let meeting = await Meeting.find({
     createdAt :  {$gte: today, $lt: tomorrow}

Answered By – Đăng Khoa Đinh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published