0
votes

I want to update document with rather complex scheme.

I want to do it with atomic update (not modify it in memory, and then call the .save() ).

Push items into mongo array via mongoose - actually explains how to push items into array. But my case is more complex.

const eventSchema = new Schema( { name: { type: 'String' },

sessions: {
    type: [
        {
            id: {
                type: 'Number'
            },
            voters: {
                type: [
                    'String'
                ]
            }
        }
    ]
}

});

///////////////////////////////////////////////////////////

event
    |
    _id 
    |
    name
    |
    sessions[object, object ...]
             |
             id
             |
             voters[string, string ...]

I have event id (_id), session (id) and need to add/delete items into voters array.

EventModel.update(
    { _id: event._id }, 
    { $push: { sessions[?? I have to find session by session.id ??]: "Jhon" } },
    done
);
1

1 Answers

0
votes

So you want to add/remove items in your voters array, that is located in your sessions array. You would use the positional operator $ for the array (https://docs.mongodb.com/manual/reference/operator/update/positional/)

EventModel.update(
    {_id: event._id, "sessions.id": event.sessionId},
    {$push: {"sessions.$.voters": "newStringToAdd"}
)