【问题标题】:Update hotel room reservation array - mongoose更新酒店房间预订数组 - mongoose
【发布时间】:2021-07-01 00:38:47
【问题描述】:

我正在开发酒店客房预订系统。以下是 Room 模型中的属性。

rId: String,
        allocation: [{
            date: Number, // 210403 == 2021-04-03
            slots: [{
                type: mongoose.Schema.Types.Mixed,
                ref: 'reservation',
                maxItems: 48
            }]
        }],
        _active: Boolean

这个“槽”是一个包含 48 个项目(30 分钟时间槽)的数组。在这里,我想用用户输入更新这个数组。例如,如果用户想保留 2.30 - 3.30 之间的时间,我想更新它数组中的两个插槽“保留”。 以下代码是用于预订的控制器

reservation
        .save(reservation) //Save reservation data
        .then((data) => { // Update room slots
            var dt = req.body.checkInDate.substr(0, 10); // extract date from user input
            var tm = req.body.checkInDate.substr(11, 5); // extract time
            dt = dt.replace(/-/g, '');  // 210403 == 2021-04-03
            tm = tm.replace(/:/g, '.');
            console.log(tm)
            console.log(dt)
            Room.findOneAndUpdate({ rId: rId }, { //Update time slot
                $push: {
                    allocation: [{
                        date: dt,
                        slots: [{ tm }]
                    }]
                }
            })

以上代码不工作。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 不工作——怎么办?你有错误吗?您没有看到的期望行为是什么?
  • 请添加带有预期输出的样本数据,如果可能的话mongoplayground.net
  • @ChristianFritz 下面我提供了我现在得到的输出。它不会在新预订时更新
  • @TusharGupta-curioustushar 下面我提供了我现在得到的输出。它不会在新预订时更新

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


【解决方案1】:

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

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

db.collection.update(
  { rId: 1, "allocation.date": 20190701 },
  { $push: { "allocation.$[a].slots": { a: 1, b: 2 } } },
  { arrayFilters: [ { "a.date": 20190701 } ]}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 2012-03-27
    • 2016-02-23
    • 2011-08-18
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多