I’m using Mongoose with TypeScript and TypeScript is not able to infer that subdocuments have an _id
field.
I’ve two Mongoose models:
// User.ts
export const UserSchema = new Schema({
email: { type: String, required: true }
});
export default model('User', UserSchema);
// Score.ts
export const ScoreSchema = new Schema({
score: { type: Number, required: true },
owner: { type: UserSchema, required: true },
});
export default model('Score', ScoreSchema);
This is the code that uses the Score model:
const score = await Score.findById(id);
if (score.owner._id.toString() === adminId) { // TypeScript error occurs here: field `_id` doesn't exist
console.log("Admin mode");
}
Field _id
does exist on the object returned by findById
. How can I setup Mongoose/TypeScript/my schemas so that this error disappears.
New contributor
csmathhc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.