简体   繁体   中英

Updating a field in a nested object when multiple conditions are met using Mongoose

I have a data model with nested objects, and I'd like to update the 'available' field to 'reserved' using the main object ID, plus the date and time associated with the nested object. Here's my data...

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

And the code I'm trying...

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'
            }
        })

Yet, the object won't update and set the status to 'reserved'. Can anyone spot what I'm doing wrong? Should I try to access the particular object using different conditions?

EDIT : Through trial and error, I think the problem is that the 'find' part returns the parent object, and all of its sub-objects in the 'availability' array are returned. The the 'update' part doesn't know which 'status' to update, and is failing at this point.

I was returning the date and time from a form in the front end and thought that I could identify the object in the array from it's parent ID plus the date and time of the reservation.

So I suppose my question should be, as the id returned in the URL is the parent object ID, is there a way to uniquely extract a specified availability object (eg. 5bf2c3bb8b95bd3a7cb3eabe) and update it's status to 'reserved'?

EDIT 2 : I can also 'find' an item by it's 'availability._id' but the full parent object is returned, so the 'update status' part doesn't work as it's too broad.

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
        }
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM