Typegoose and Mongoose - Cast to ObjectId failed for value when saving nested list of schema types

428 views Asked by At

Getting this error:

Competition validation failed: results.0: Cast to ObjectId failed for value "{ name: 'David'}"

Here's the parent:

class Competition {
  @prop()
  compName: string
  

  @prop({ ref: () => CompetitionParticipant})
  results: Ref<CompetitionParticipant>[]
}

Here's the child:

class CompetitionParticipant  {

  @prop()
  name: string
}

Here's how it's being called:

const CompetitionResults = getModelForClass(Competition)
await new CompetitionResults({compName: 'competition name', results: [{name: 'David'}]}).save()
1

There are 1 answers

0
hasezoey On

this is because you try to save value { name: 'David' } as an reference, which is not supported (read here for more), you need to either provide and valid _id (in this case an ObjectId), or an instance of mongoose.Document

the easiest workaround is to manually loop over the array and save them individually (like in an bulk-insert call, or in an for loop over the array)