ADAMJR
ADAMJR

Reputation: 2738

Mongoose - Cast to ObjectId failed, Multiple IDs

return new SavedMember({
    id: member.id, // ID of the user
    guildId: member.guild.id // ID of the guild
}).save();

gives error:

  message: 'Cast to ObjectId failed for value "218459216145285121" at path "_id" for model "member"',    
  name: 'CastError',
  model: Model { member }

member.ts

const memberSchema = new Schema({
    _id: Types.ObjectId,
    id: String,
    guildId: String,
    xpMessages: { type: Number, default: 0 },
    warnings: { type: Array, default: [] }
});
...
export const SavedMember = model<MemberDocument>('member', memberSchema);

Repo: https://github.com/theADAMJR/2pg-dashboard

Upvotes: 0

Views: 215

Answers (1)

Rodrigo
Rodrigo

Reputation: 81

Based on this other answer here:

Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

So, when you try to add a new document, the id property refers to _id

Upvotes: 2

Related Questions