CastError:使用populate转换为ObjectId

时间:2018-05-20 08:23:46

标签: javascript node.js mongodb mongoose

我有UserSchemaCreditSchema

const UserSchema = new Schema({
  credit: {
    type: Schema.Types.ObjectId,
    ref: 'Credit'
  }
})

const CreditSchema = new Schema({
  userId: Schema.Types.ObjectId,
  credit: {
    type: Number,
    default: 0
  }
})

然后我做了这2个动作。

//save to credit
await new Credit({
  userId: mongoose.Types.ObjectId('5a3e76ce914e1d1bd854451d'),
  credit: 100
}).save()

已成功插入数据。

enter image description here

//then I try to populate credit
await User.find({}).populate('credit').exec()

我收到错误

(node:17858) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "0" at path "_id" for model "Credit"

为什么呢?我在保存新的信用文件时,我以为我已经将字符串转换为ObjectId了?

0 个答案:

没有答案