Update array inside a mongoose document

Viewed 38

I have a mongoose schema which has a field like so

    Week1ScheduleEntries: [{
          PlayerName: String,
          Slots: { type: Array, default:[]}
        }],

I am trying to update the Slots array based on a certain condition, inside a for loop. This is what I have tried so far:-

    for (let i=0; i<activeTournamentRecord.Week1ScheduleEntries.length; i++){
          playerIsActive = false
          let idNumber = activeTournamentRecord.Week1ScheduleEntries[i]._id
          if(activeTournamentRecord.Week1ScheduleEntries[i].PlayerName === player){
            console.log(idNumber)
            playerIsActive = true
            try{
                const updatedTournamentRecord = await Tournament.findOneAndUpdate({_id: idNumber},
                  {$set: {"Slots": {"Slots": slotArray }} }
                )
            } catch (err) {
              const error = new HttpError(
                'Cant Find Tournament. ',
                500
              );
              return next(error);
            }
            break
          }

The $set is unfortunately not working. Am I missing something? Can someone help?

1 Answers
                const updatedTournamentRecord = await Tournament.findOneAndUpdate({_id: idNumber},
                  {$set: {"Slots": {"Slots": slotArray }} }
                )

try this

                const updatedTournamentRecord = await Tournament.findOneAndUpdate({_id: idNumber},
                  {$set: {"Slots.$[]": slotArray } }
                )
Related