1

Hello I have a document with some user records.

    "profile":{
     "records":[
              {
                "classId":   "LngdsQfL",
                "moduleId":  "5CDEezDJ",
                "sectionId": "nFMu3mwa",
                "dateFinished": "",
                "dateOpened": "2017-11-15T19:48:20.819Z"
              },
              {
                "classId":   "7Smq5sG",
                "moduleId":  "5CDEezDJ",
                "sectionId": "nFMu3mwa",
                "dateFinished": "",
                "dateOpened": "2017-11-15T19:19:08.669Z"
              }
            ]
      }

But when I am trying to update the second record the query updates the first one. And the second one stays the same.

 var classId= "7Smq5sG";
 var moduleId = "5CDEezDJ";
 var sectionId = "nFMu3mwa";
 var date = new Date();

Users.update(
              { _id:Meteor.userId() ,

                'profile.records.classId' : classId,
                'profile.records.moduleId' : moduleId,
                'profile.records.sectionId' :  sectionId,
              },{
              $set : { 
                "profile.records.$.dateOpened": date
                }
             });
    }

What am I missing?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
dionysosz
  • 143
  • 1
  • 5
  • 17
  • How can you tell that you are updating the first record? What is your `Meteor.userId()`? – Andrija Ćeranić Nov 15 '17 at 21:30
  • I am using Meteor js and Meteor.userId() returns the id of the current user. When I check my database, I can see that the first record is updated. – dionysosz Nov 15 '17 at 21:35
  • That's only possible once you're on MongoDB v3.6 which will be released within the next hours literally. – dnickless Nov 15 '17 at 21:46
  • Also see this link here: https://stackoverflow.com/questions/39326843/how-to-update-property-in-multiple-objects-in-an-array-for-one-document-in-meteo – dnickless Nov 15 '17 at 21:48
  • Thanks for replies. I don't want to update multiple documents though, but only one. And the weird thing is that the wrong document is updated. – dionysosz Nov 15 '17 at 21:52

1 Answers1

3

Try to use a request as follows:

Users.update(
  {_id:Meteor.userId(),
   'profile.records': {$elemMatch: {
                                     'moduleId': {$eq: moduleId},
                                     'sectionId': {$eq: sectionId},
                                     'classId': {$eq: classId}
                                   }
                      }
  },
  {$set: {'profile.records.$.dateOpened': date}});

It uses $elemMatch operator to find array element that matches multiple query criteria.

Andriy Simonov
  • 1,276
  • 1
  • 11
  • 19