0

How to I find right course_id and and push a "myclass2" to classes_id field which is an array?

I have got this but it added an extra row to classes

let data = Meteor.users.update({_id: Meteor.userId(), "classes.course_id": course_id}, {
   $push: {
        "classes": {
            "classes_id": [class_name]
        }
    }}
)

Wrong update:

{
  "_id": "RoFFcaAfXBeR2napZ",
  "emails": [
    {
      "address": "[email protected]",
      "verified": false
    }
  ],
  "classes": [
      {
         "course_id": "svesvinfdsgrvnekuktndvsk",
         "classes_id": ["myclass1"]
      },
      {
         "course_id": "rgjjgdcrvnevghjcdvbbvddv",
         "classes_id": ["myclass1"]
      },
      {
         "classes_id": ["myclass2"]<----wrong update
      },
  ],
  "courses": [
    "qwmZdgQbrZ3rmHdN8"
  ]
}

Before Adding

{
  "_id": "RoFFcaAfXBeR2napZ",
  "emails": [
    {
      "address": "[email protected]",
      "verified": false
    }
  ],
  "classes": [
      {
         "course_id": "svesvinfdsgrvnekuktndvsk",
         "classes_id": ["myclass1"]
      },
      {
         "course_id": "rgjjgdcrvnevghjcdvbbvddv",
         "classes_id": ["myclass1"]
      },
  ],
  "courses": [
    "qwmZdgQbrZ3rmHdN8"
  ]
}

How do I achieve this? Add myclass2 to classes_id if i can find course_id

{
  "_id": "RoFFcaAfXBeR2napZ",
  "emails": [
    {
      "address": "[email protected]",
      "verified": false
    }
  ],
  "classes": [
      {
         "course_id": "svesvinfdsgrvnekuktndvsk",
         "classes_id": ["myclass1", "myclass2"]<----correct
      },
     {
         "course_id": "rgjjgdcrvnevghjcdvbbvddv",
         "classes_id": ["myclass1"]
      },
  ],
  "courses": [
    "qwmZdgQbrZ3rmHdN8"
  ]
}

2 Answers 2

2

You can use the positional $ operator.

function addClassId(userId, courseId, classId) {
  c1.update({
    _id: userId,
    'classes.course_id': courseId
  }, {
    $push: {
      'classes.$.classes_id': classId
    }
  });
};  

It will get the first match from the classes array and push classId into its classes_id array.

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

1 Comment

Then you should accept it. This makes others understand that the issue is resolved (even from the search) and is, therefore, a good practice.
0

This works!

let data = Meteor.users.update({_id: Meteor.userId(), "classes.course_id": course_id}, {
     $push: {"classes.$.classes_id": class_name}
})

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.