【问题标题】:How can I only print today's reservations from the MongoDB?我如何只能从 MongoDB 打印今天的预订?
【发布时间】:2021-07-01 06:32:18
【问题描述】:

i tried

我是新手编码员。我的学习项目是时间表。

我想打印一份预订清单,例如 2021-04-06。

但不仅是 2021-04-06。

所有预订日期均已打印。

全部失败...

我使用 NodeJS、express、mongoDB、mongoose。

帮帮我。

User Schema({
    name: user1
    clients: [
        client1,
        client2
    ]
});
Client Schema({
    name: client1
    phone: 00000000,
    gender: 1,
    reservation:[
        {
            date: 2021-04-06T00:00:00.000Z,
            time: "14:00"
            cancel: "off",
            noshow: "on",
        },
        {
            date: 2021-04-10T00:00:00.000Z,
            time: "14:00"
            cancel: "off",
            noshow: "off",
        }
    ],
    memo: String,
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }
},
{
    name: client2
    phone: 00000002,
    gender: 0,
    reservation:[
        {
            date: 2021-04-06T00:00:00.000Z,
            time: "10:00"
            note: "first"
            cancel: "off",
            noshow: "on",
        },
        {
            date: 2021-04-12T00:00:00.000Z,
            time: "14:00"
            note: "second"
            createdAt: Date,
            cancel: "off",
            noshow: "off",
        }
    ],
    memo: String,
    user: user1
})

【问题讨论】:

  • 您的架构与屏幕截图中的查询不匹配。是reservation.date 还是reserve.date
  • 请不要粘贴截图,提供格式化文本的代码。见meta.stackoverflow.com/a/285557/3027266
  • 每当需要处理日期和时间时,我推荐moment.js 库。它让您的生活更轻松。
  • 为什么将数据和时间值存储在不同的字段中?最好只使用一个字段,Date 对象具有日期和时间组件。
  • 谢谢。它在照片中的显示方式有所不同,但实际上它被统一为保护区。我使 html 标记输入更容易,我将时间和日期分开。最好把它们结合起来,所以我来做。

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

演示 - https://mongoplayground.net/p/m39zdyqq8id

使用聚合查询

使用$unwind 拆分单个文档并使用$match 按日期过滤。

db.collection.aggregate([
  { $unwind: "$reservation" },
  { $match: { "reservation.date": ISODate("2021-04-06") } }
])

【讨论】:

  • 谢谢。我就这样找到了自己的路。在 CLI 中,此方法非常有效。但在猫鼬或 javascript 中不应该这样。 {$ match: {"reserve.noshow": "on"}} 这很好用。日期搜索方法似乎有问题。我尝试了几件事,但失败了。 {$ match: {"reserve.noshow": {$ date: '2021-04-06'}}}; // const a = '2021-04-06'; const b = a.toISOString(); {$ match: {"reserve.noshow": b}}; // const c = new date ('2021-04-06'); {$ match: {"reserve.noshow": c}}; 全部失败..有什么办法吗?
  • i ``` { $unwind: "$reserve" }, { $match: { "reserve.date": new Date("2021-04-05T00:00:00.000Z") } ```我成功了。在 Mongoose 中,您必须设置一个新日期(“2021-04-05”)。非常感谢!
  • @seongjin 很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
  • 2013-06-20
  • 2020-06-29
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
相关资源
最近更新 更多