0

I'm trying to use some nested arrays in mongoDB but after several hours fighting with the mongo docs and several other SO questions. I'm thinking I might be doing something terribly wrong. The code below is supposed to update the confirms array in the confirms array but it won't ever do anything but add new entries. Any help would be appreciated.

Events.update({_id: eventId, "confirms.person": personId}, {
    $set: {
        "confirms.$.person": personId,
        "confirms.$.confirmed": isConfirmed,
        "confirms.$.timestamp": new Date()
    }
});

And here is a sample of the data I'm trying to operate on, it is currently WRONG because a personId should be unique.

{
    "_id": "RnE4PaPSZ9FC9MAAQ",
    "eventTitle": "Epic lan PARTY!!!!!",
    "eventDate": "31/07/2015",
    "confirms": [{
        "person": "jjoqekYYaA6n8nYvs",
        "confirmed": true,
        "timestamp": ISODate("2015-07-25T17:15:28.212Z")
    }, {
        "person": "jjoqekYYaA6n8nYvs",
        "confirmed": true,
        "timestamp": ISODate("2015-07-25T17:16:50.485Z")
    }
    }]
}

Just in case it might turn out to be relevant, i'm working in meteor js.

Lucas Huang
  • 3,998
  • 3
  • 20
  • 29
Tristan
  • 1,004
  • 7
  • 14
  • When running your query in the mongo shell using the data you provided (with only one `confirms` array element), the update works perfectly. From a mongodb shell perspective, your query is correct. Try running the query in your db using the shell. If it works then this could be a meteor issue. – whyceewhite Jul 26 '15 at 19:23
  • @whyceewhite thanks for that, looked again in all the surrounding code and found my mistake. – Tristan Jul 27 '15 at 07:32

1 Answers1

0

To update the element of an array which is the variable of a Collection item you could do this:

  1. Get the array:

    var arr = Events.findOne({_id: eventId}).confirms;

  2. Do your operation

  3. Update old array with modified array:

    Events.update({_id: eventId}, {$set: {confirms: arr}});

In case of problems with step 2: you could iterate through the array checking if this.person === personId then set this.confirmed = isConfirmed & this.timestamp = new Date.

There might be ways of operating on arrays within Mongo but this one works for sure.

Milant
  • 1
  • 3