I have been working on mongoose + typescript for quite some time now. But I am facing this issue while creating CustomDoc interface for my schema.
Typescript is not validating the returned document from mongoose query, it shows type any .
Custom Doc Interface
interface UserAttrs {
name: string;
email: string;
password: string;
}
interface UserDoc extends mongoose.Document { // <== here
name: string;
email: string;
password: string;
isAdmin: Boolean;
createdAt: Date;
}
interface UserModel extends mongoose.Model<UserDoc> {
build: (attrs: UserAttrs) => UserDoc;
}
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now() },
}
);
userSchema.statics.build = (attrs: UserAttrs) => {
return new User(attrs);
};
export const User = mongoose.model<UserDoc, UserModel>("User", userSchema);
The error / issue
As per my understanding, it should have a type of UserDoc
or undefined
. That is the reason why I am not able validate while destructuring user properties off of user document, which makes no sense to use TS like this.
Try this out instead:
interface UserAttrs {
name: string;
email: string;
password: string;
}
interface UserDoc extends UserAttrs, mongoose.Document {
isAdmin: Boolean;
createdAt: Date;
}
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now() },
}
);
userSchema.statics.build = (attrs: UserAttrs) => {
return new User(attrs);
};
export const User = mongoose.model<UserDoc>("User", userSchema);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.