Home > Blockchain >  Find data by today's date in mongoose
Find data by today's date in mongoose

Time:07-08

I have data like this in my database. I want to get data by today's date. I have described my problem here.

"todayOrders": [
            {
                "_id": "62c5746105e721df2619d84f",
                "invoiceId": "TME1657107517717",
                "subTotal": 14000,
                "laborCharge": 500,
                "discount": 200,
                "total": 14300,
                "cash": 13000,
                "due": 1300,
                "status": false,
                "createdAt": "2022-07-06T11:39:13.128Z",
                "updatedAt": "2022-07-06T11:39:13.128Z",
                "__v": 0
            },
            {
                "_id": "62c6c7f0e0591a84336e5364",
                "invoiceId": "TME1657194446227",
                "subTotal": 220000,
                "laborCharge": 1000,
                "discount": 200,
                "total": 220800,
                "cash": 220800,
                "due": 0,
                "status": false,
                "createdAt": "2022-07-07T11:48:00.067Z",
                "updatedAt": "2022-07-07T11:48:00.067Z",
                "__v": 0
            }
        ]

Now I want to find data based on createdAT by today's new date. I have tried this but it returns all the data,

const todayOrders = await Order.find({
            createdAt: {$gte : new Date() },
            createdAt: {$lt : new Date() }
        }).populate({ path: 'userId' }).populate({ path: 'orderPorducts.productId' });

My expected result on today's date could be like this,

[{
                "_id": "62c6c7f0e0591a84336e5364",
                "invoiceId": "TME1657194446227",
                "subTotal": 220000,
                "laborCharge": 1000,
                "discount": 200,
                "total": 220800,
                "cash": 220800,
                "due": 0,
                "status": false,
                "createdAt": "2022-07-07T11:48:00.067Z",
                "updatedAt": "2022-07-07T11:48:00.067Z",
                "__v": 0
            }
]

CodePudding user response:

You need to create the correct start and end times. You can use moment.js to do it easily or you can create a start date for today.

const start = new Date().toDateString();
const todayOrders = await Order.find({
            createdAt: {$gte : start } // it will get you records for today's date only
        }).populate({ path: 'userId' }).populate({ path: 'orderPorducts.productId
  • Related