[英]Mongoose + Typescript custom doc interface not working
I have been working on mongoose + typescript for quite some time now.我已经在 mongoose + typescript 上工作了很长一段时间。 But I am facing this issue while creating CustomDoc interface for my schema.
但是我在为我的模式创建CustomDoc 接口时遇到了这个问题。
Typescript is not validating the returned document from mongoose query, it shows type any . Typescript 未验证 mongoose 查询返回的文档,它显示类型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
.根据我的理解,它应该有一种
UserDoc
或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.这就是为什么我无法在从用户文档中解构用户属性时进行验证的原因,这样使用 TS 是没有意义的。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.