【问题标题】:Find data by today's date in mongoose在猫鼬中查找今天日期的数据
【发布时间】:2022-07-07 20:20:42
【问题描述】:

我的数据库中有这样的数据。我想在今天之前获取数据。我已经在这里描述了我的问题。

"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
            }
        ]

现在我想在今天的新日期之前根据 createdAT 查找数据。我已经尝试过了,但它返回了所有数据,

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

我今天的预期结果可能是这样的,

[{
                "_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
            }
]

【问题讨论】:

    标签: node.js mongodb express mongoose mongodb-query


    【解决方案1】:

    您需要创建正确的开始时间和结束时间。您可以使用 moment.js 轻松完成,也可以创建今天的开始日期。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多