Home > Net >  Can't iterate over mongodb array
Can't iterate over mongodb array

Time:11-29

We are looking for a user in the database by '_id'

   "_id": "6381e7c6bf8892cf05c7c798",
    "username": "Teacher",
    "email": "[email protected]",
    "role": "teacher",
    "avatar": "fixtures/teacher.jpg",
    "token": "KNuSF7sscU3EJsMetUFKi",
    "authentication": true,
    "myCourses"

and

It is necessary to get a suitable object from the array using 'aggregate', which we find by the 'course' field and change the 'status' in it

   "myCourses": [
        {
            "course": "6381e7c6bf8892cf05c7c7b3",
            "status": true,
            "_id": "6381e80f12d633b2e6c35fbd"
        },
        {
            "course": "6381edab4f212193837ab575",
            "status": true,
            "_id": "6381edc54f212193837ab57c"
        }
    ],

I have tried the following methods

const test = await User.find({ _id: userId, myCourses: {$elemMatch: {course: courseId}} })
const test = await User.find(userId, { courseId: {$in : myCourses} })
const updateCourseStatus = user.myCourses.find(elem => elem.course.toString() === courseId)

the last method works but I don't think it's correct

CodePudding user response:

If you want to update in myCourses course status. Filter the document by _id and also the course you want to update by courseId. Use pointer operator $ to set value in pointed object property. Read the documentation here

User.update({
  _id: userId,
  "myCourses.course": courseId
},
{
  $set: {
    "myCourses.$.status": newStatus
  }
})

Try sample
example

CodePudding user response:

Another option to change "status" given "myCourses.course" using "arrayFilters" is:

db.user.update({
  "_id": userId
},
{
  "$set": {
    "myCourses.$[elem].status": newStatus
  }
},
{
  "arrayFilters": [
    {
      "elem.course": courseId
    }
  ]
})

Try it on mongoplayground.net.

  • Related