0

I have a similar issue to this question.

I'm trying to create a new field using "findAndUpdate". I've tried all the methods, $set, $push, $addSet... none of them seem to be working and I keep getting the same error.

Here's the code:

router.post('/accept', auth, async (req, res) => {        
  const useremail = user.email
  const originalEvent = await Event.findOneAndUpdate({eventId: 61469041, isOrganizer: true, "attendees.email": useremail},
            {"$push":{"attendees.status" : "accepted"}},
            {new: true})
            res.status(200).json({originalEvent, event})
          
          } 
          catch (e) {
          res.status(400).json({ msg: e.message, success: false });
        }
        });

Here's the error code:

"Cannot create field 'status' in element {attendees: [ { _id: ObjectId('5f80a02a82dceb2810e0aa66'), email: "bob@gmail.com", name: "Bob" } ]}"

Here's the object I'm trying to update:

{
    "organizer": {
      "email": "alex@gmail.com",
      "name": "Alex"
    },
    "_id": "5f80a02a82dceb2810e0aa65",
    "title": "Go to the beach",
    "eventId": 61469041,
    "isOrganizer": true,
    "user": "5f05f23417ca6ab69ccc4cf2",
    "attendees": [
      {
        "_id": "5f80a02a82dceb2810e0aa66",
        "email": "bob@gmail.com",
        "name": "Bob"
      }
    ],
    "__v": 0,
  }

Expected outcome:

{
    "organizer": {
      "email": "alex@gmail.com",
      "name": "Alex"
    },
    "_id": "5f80a02a82dceb2810e0aa65",
    "title": "Go to the beach",
    "eventId": 61469041,
    "isOrganizer": true,
    "user": "5f05f23417ca6ab69ccc4cf2",
    "attendees": [
      {
        "_id": "5f80a02a82dceb2810e0aa66",
        "email": "bob@gmail.com",
        "name": "Bob",
        "status": "accepted"
      }
    ],
    "__v": 0,
  }

SOLVED with this:

  const originalEvent = await Event.findOneAndUpdate({eventId: eventId, "isOrganizer": true, 
    "attendees": {$elemMatch: {email: useremail}}
  },
    { $set: { "attendees.$.status": "accepted"} }
      )
    
    res.status(200).json(originalEvent)
  
  } 
morethan1
  • 35
  • 6

1 Answers1

1

Referencing attendees.status doesn't make sense because in your schema attendees is not an object (with fields such as status) but an array. But you can do it differently. If you have the index of the attendee you want to mutate, you can do { $set: { "attendees.0.status": "accepted" } }, where 0 is the index in the array.


Also, with regards to the first half of your question, the error you're seeing is because $push works on arrays. So in order for your operation to work, you'd have to first initialize such an object {attendees: { status: [] } }.

If the field is not an array, the operation will fail. (docs)

Gunar Gessner
  • 2,331
  • 23
  • 23