简体   繁体   中英

Update an object inside nested array using mongoose

My mongo schema looks like this, I want to update a flashcard object located in an array of flashcard also located in array of subject.

const classrooms = new mongoose.Schema({
    name: String,
    year: String,
    student: [
        {
            firstname: String,
            lastname: String,
            mail: String,
            userId: String,
        }
    ],
    subject: [
        {
            subjectId: String,
            flashcard: [
                {
                    title: String,
                    tag: []
                }
            ]
        }
    ]
});

what I am doing is

const flashcard = await classroomModel.findOneAndUpdate({
    _id : classroomId,
    "subject" : {
        "subjectId" : subjectId,
        "subject.flashcard" : {
            "_id" : flashcardId
        }
    },
    "$set" : {
        "flashcard.title" : "new title"
    }
})

but this is deleting all flashcards located inside an object. any help would be appreciated.

You needarrayFilters to specify the (to-be-updated) flashcard document that meets the criteria for subject and flashcard .

db.collection.update({
  _id: 1//classroomId,
  
},
{
  "$set": {
    "subject.$[subject].flashcard.$[flashcard].title": "new title"
  }
},
{
  arrayFilters: [
    {
      "subject.subjectId": 1//subjectId
      
    },
    {
      "flashcard._id": 1//flashcardId
      
    }
  ]
})

Sample Mongo Playground

Although i accepted @yong shun which is the best approach, another way to do it in case you don't like mongoose syntax :


      const classroom = await classroomModel.findOne(
        {
          _id: 1 //classroomId,
        },
      )

      const subject = classroom.subject.find(
        (currentSubject: any) => {
          return currentSubject.subjectId == 1 //subjectId
        }
      )

      const flashcard = subject.flashcard.find(
        (currentFlashcard: any) => {
          return currentFlashcard._id == 1 //flashcardId
        }
      )
      flashcard.title = "my new title";
      await classroomModel.updateOne(classroom);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM