I have UserSchema
and CreditSchema
const UserSchema = new Schema({
credit: {
type: Schema.Types.ObjectId,
ref: 'Credit'
}
})
const CreditSchema = new Schema({
userId: Schema.Types.ObjectId,
credit: {
type: Number,
default: 0
}
})
Then I do these 2 action.
//save to credit
await new Credit({
userId: mongoose.Types.ObjectId('5a3e76ce914e1d1bd854451d'),
credit: 100
}).save()
The data been inserted successfully.
//then I try to populate credit
await User.find({}).populate('credit').exec()
I got error of
(node:17858) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "0" at path "_id" for model "Credit"
Why? I thought I already cast string to ObjectId when I was saving a new credit document?