0

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?

istvan kolkert
  • 122
  • 1
  • 10

1 Answers1

1
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);
})
Nayan
  • 638
  • 6
  • 15
  • Thanks for the response Nayan but how is this supposed to work? You are not even giving the lessonID? – istvan kolkert May 05 '20 at 10:02
  • Okay my assumption is `req.params.id` is lessonID. if that is not the case then the first argument of findOneAndUpdate will change with that find query. Second argument is the update you want in the document and the third one is option where `new:true` will return updated document. – Nayan May 05 '20 at 10:14
  • Ah so like this? let myLessonDB = await myLessonSchema.findOneAndUpdate({_id:req.params.id, 'lessons.lesson': lessonID}, {$set: { 'lessons.$.present': true }}, {new:true}); – istvan kolkert May 05 '20 at 10:17
  • this will work but lessons.lesson:lessonID condition is not useful as _id is unique and with that Mongo will find only one doc and it that single doc has same lessonID then it will return otherwise the final result will be null. – Nayan May 05 '20 at 10:37
  • Yea but lessons is an array and it needs to edit a specified value in that array which is located using lessonID – istvan kolkert May 05 '20 at 13:00