【问题标题】:Typegoose and Mongoose - Cast to ObjectId failed for value when saving nested list of schema typesTypegoose 和 Mongoose - 保存模式类型的嵌套列表时,转换为 ObjectId 的值失败
【发布时间】:2021-03-23 10:58:29
【问题描述】:

收到此错误:

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

这是父级:

class Competition {
  @prop()
  compName: string
  

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

这是孩子:

class CompetitionParticipant  {

  @prop()
  name: string
}

它的名称如下:

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

【问题讨论】:

    标签: mongodb typescript mongoose typegoose


    【解决方案1】:

    这是因为您尝试将值 { name: 'David' } 保存为不支持的参考 (read here for more),您需要提供有效的 _id(在本例中为 ObjectId),或者mongoose.Document的实例

    最简单的解决方法是手动循环数组并单独保存它们(例如在批量插入调用中,或在数组上的 for 循环中)

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2013-03-24
      • 2021-09-05
      • 2021-03-09
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2020-07-28
      • 2020-04-18
      相关资源
      最近更新 更多