Home > Enterprise >  Get objects from database of date between yesterday and today
Get objects from database of date between yesterday and today

Time:11-15

I have the following schema.

const dish = new Schema({
    name: {
        type: string,
    },
        createdAt: {
        type: Date,
    },
)

I want to get the dishes that are created between yesterday 12AM to today's 12AM.

CodePudding user response:

const dish = await Dish.aggregate([
 {
    $match: {
        $and: [
            { createdAt: { $lt: new Date(new Date().setHours(0, 0, 0))}},
            { createdAt: { $gte: new Date(new Date().setHours(0, 0, 0) - 24 * 60 * 60 * 1000)}}
       ]
     }
   }
]);

Edited: Here is the explanation.

new Date() give you a date like 2022-11-15T22:14:00.000 00:00 but new Date().setHours(0,0,0) will set the values to 12AM but also gives you value in millisecond like 1668449700000.

Your createdAt has value in date like 2022-11-15T22:14:00.000 00:00. Using { $lt: new Date().setHours(0, 0, 0)}} it will try to compare value between a date and a integer [2022-11-15T22:14:00.000 00:00 , 1668449700000] so you will get a wrong result.

So you need to put that into a new Date() to get the value in Date so that the $lt can compare properly. new Date(new Date().setHours(0, 0, 0))} will be equal to new Date(1668449700000) which will give you a date value and the $lt will also work properly.

As for the second condition, 24 * 60 * 60 * 1000 is 1 day in millisecond. So I've subtracted that to get the millisecond of yesterday's 12AM.

  • Related