Meteor mongo updates 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 am new to mongoDB and I read other questions about updating a nested array and I cannot do it right. I want to change startDate and endDate for a user with a given user. My problem is that it always pushes the new object to the array instead of changing the object with the given user.

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

I will really be happy to help.

+4
source share
2 answers

, , , $elemMatch , . , " " , . "dot notation" .

- $push, "" . "", $set:

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

, positional $ , " " $set "" , "".

+9

" , Meteor.userId() , userID, startDate endDate? - justdiehard 14 20:20"

, Meteor Accounts, ,

Accounts.createUser(YOU_USER_SCHEME)
0

All Articles