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}
});