Mossar
Mossar

Reputation: 435

Meteor mongo updating nested array

Example document:

{
"_id" : "5fTTdZhhLkFXpKvPY",
"name" : "example",
"usersActivities" : [ 
    {
        "userId" : "kHaM8hL3E3As7zkc5",
        "startDate" : ISODate("2015-06-01T00:00:00.000Z"),
        "endDate" : ISODate("2015-06-01T00:00:00.000Z")
    }
]
}

I'm new in mongoDB and I read other questions about updating nested array and I can't do it properly. What I want to do is to change startDate and endDate for user with given userId. My problem is that it always pushes new object to array instead of changing object with given userId.

Activity.update( 
    _id: activityId, usersActivities: {
         $elemMatch: {
             userId: Meteor.userId()
         }
     }},
    {
        $push: {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
         }
    }
);

I will be really glad of help.

Upvotes: 4

Views: 3747

Answers (2)

Jefferson Desouza
Jefferson Desouza

Reputation: 1

"What if Meteor.userId() does not exist, how to insert the whole of object with userID, startDate and endDate? – justdiehard Jun 14 at 20:20"

If you try to put new, you should take a look at Meteor Accounts package, there are methods like

Accounts.createUser(YOU_USER_SCHEME)

Upvotes: 0

user3561036
user3561036

Reputation:

So the first thing to say here is the $elemMatch is not required in your case as you only want to match on a single array property. You use that operator when you need "two or more" properties from the same array element to match your conditions. Otherwise you just use "dot notation" as a standard.

The second case here is with $push, where that particular operator means to "add" elements to the array. In your case you just want to "update" so the correct operator here is $set:

Activity.update(
    { "_id": activityId, "usersActivities.userId": Meteor.userId() },
    {
        "$set": {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
        }
    }
)

So the positional $ operator here is what matches the "found index" from the array element and allows the $set operator to "change" the elements matched at that "position".

Upvotes: 9

Related Questions