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?

5
  • How can you tell that you are updating the first record? What is your Meteor.userId()? Commented Nov 15, 2017 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. Commented Nov 15, 2017 at 21:35
  • That's only possible once you're on MongoDB v3.6 which will be released within the next hours literally. Commented Nov 15, 2017 at 21:46
  • Also see this link here: stackoverflow.com/questions/39326843/… Commented Nov 15, 2017 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. Commented Nov 15, 2017 at 21:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.