猫鼬中引用集合的默认值

Hok*_*imo 4 mongoose mongodb node.js

我有一个用户个人资料,我有一个“收入”字段,它在架构中看起来像这样

收入:{ type: Schema.Types.ObjectId, ref: 'Earning' }

创建新用户时如何为收入字段设置默认值?我不能这样做

earning: {
    type: Schema.Types.ObjectId,
    ref: 'Earning',
    default: 0
  }
Run Code Online (Sandbox Code Playgroud)

我在路径“earning”处收到值“0”的 Cast to ObjectId failed 错误

ait*_*han 6

您在这里做错的是尝试在 ID 字段上投射数字。由于它是另一个对象 Id 字段的引用,因此不能将其设置为 0。您需要做的是null在数据库中创建用户时进行设置,并使用赚取的空值对其进行初始化。喜欢:

earning: {
  type: Schema.Types.ObjectId,
  ref: 'Earning',
  default: null
}
Run Code Online (Sandbox Code Playgroud)