【问题标题】:Updating a field in a nested object when multiple conditions are met using Mongoose使用 Mongoose 满足多个条件时更新嵌套对象中的字段
【发布时间】:2018-11-19 15:06:36
【问题描述】:

我有一个包含嵌套对象的数据模型,我想使用主对象 ID 以及与嵌套对象关联的日期和时间将“可用”字段更新为“保留”。这是我的数据...

{
"_id": {
    "$oid": "5bf1a675041f242cda138d1c"
},
"availability": [
    {
        "_id": {
            "$oid": "5bf2c077d5683c38afacf34b"
        },
        "date": "2018-12-20 ",
        "time": " 11:00 - 12:00 ",
        "status": "reserved"
    },
    {
        "_id": {
            "$oid": "5bf2c3bb8b95bd3a7cb3eabe"
        },
        "date": "2018-11-30",
        "time": "18:00 - 19:00",
        "status": "available"
    }
],
"name": "blah",
"price": 50,
"city": "blah",
"__v": 0
}

我正在尝试的代码...

router.get('/reserve/:id', function(req, res, next){

    //I've other stuff here that sets the correct variables according to the console.log, so str2[0] contains the date I want to find, etc.


        Pitch.findOneAndUpdate({
            id: req.params.id,
            'availability.date': 'str2[0]', //passing in 2018-11-30
            'availability.time': 'str2[1]', //passing in 18:00 - 19:00
            'availability.status': 'available'
        },
        {$set: {
            'availability.$.status': 'reserved'
            }
        })

然而,对象不会更新并将状态设置为“保留”。谁能发现我做错了什么?我应该尝试使用不同的条件访问特定对象吗?

编辑:通过反复试验,我认为问题在于“查找”部分返回父对象,并返回“可用性”数组中的所有子对象。 “更新”部分不知道要更新哪个“状态”,此时失败。

我从前端的表单返回日期和时间,并认为我可以从数组的父 ID 加上预订的日期和时间来识别数组中的对象。

所以我想我的问题应该是,由于 URL 中返回的 id 是父对象 ID,有没有办法唯一地提取指定的可用性对象(例如 5bf2c3bb8b95bd3a7cb3eabe)并将其状态更新为“保留”?

编辑 2:我也可以通过它的 'availability._id' 来“找到”一个项目,但返回的是完整的父对象,因此“更新状态”部分不起作用,因为它太宽泛了。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:
    Pitch.findOneAndUpdate({
         id: req.params.id,
        'availability.status': 'available'
           },
       {$set: {
                'availability.$.status': 'reserved',
                'availability.$.date': 'str2[0]', //passing in 2018-11-30
                'availability.$.time': 'str2[1]', //passing in 18:00 - 19:00
            }
        })
    

    【讨论】:

    • 感谢您的建议,但我认为这不是我需要的,因为我正在尝试更新相关可用性中的状态。_id。我将编辑我的原始帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2021-01-10
    • 2018-12-20
    相关资源
    最近更新 更多