我一直在学习有关使用node,typescript和mongodb的微服务的课程,而我一直困扰着这个问题几天。
我不明白,为什么接口UserModel最终需要<UserDoc>
?我知道build(attrs: userAttrs): UserDoc;
在这里我们指定了一个将在UserModel上使用的函数,它将返回一个UserDoc。但是我不明白这个interface UserModel extends mongoose.Model<UserDoc>
// an interface that describes properties that are required to create a new user
interface userAttrs {
email: string;
password: string;
}
//an interface that describes the properties that user model has. It's gonna say there's gonna be build function on user model
interface UserModel extends mongoose.Model<UserDoc> {
build(attrs: userAttrs): UserDoc;
}
//an interface thath describes properties that user document has
interface UserDoc extends mongoose.Document {
email: string;
password: string;
}
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
});
userSchema.statics.build = (attrs: userAttrs) => {
return new User(attrs);
};
const User = mongoose.model<UserDoc, UserModel>('User', userSchema);
const user = User.build({
email: 'test@gmail.com',
password: 'password',
});
console.log(user);
export { User };