istvan kolkert
istvan kolkert

Reputation: 142

Mongoose, change value in array

I am trying to update a value in an array, i tried doing it this way: Mongoose, update values in array of objects

But it doesn't seem to work for me:

let myLessonDB = await myLessonSchema.findById(req.params.id);

myLessonDB.update(
    { 'lessons.lesson': req.body.lessonID },
    { $set: { 'lessons.$.present': true } }
);

myLessonDB return this:

{"_id":"5eafff00726616772ca852e2",
"lessons":[{"level":"1","present":false,"lesson":"5eb00211154ac86dc8459d6f"}],
"__v":0}

I am trying to change a value in lessons by the lesson ID as shown but it doesn't work.
No errors or anything it looks like it cant find the object in the array

Anyone know what I am doing wrong?

Upvotes: 0

Views: 49

Answers (1)

Nayan
Nayan

Reputation: 658

let myLessonDB = await myLessonSchema.findById(req.params.id);

myLessonDB.lessons.map(oneLes => {
  if(oneLes.lesson == req.body.lessonID){
    oneLes.present = true;
  }
})

myLessonDB.save().then( finalLesson => {
  console.log(finalLesson);
})

Upvotes: 1

Related Questions