TypeScript wants to make sure we are providing the correct properties while creating a User Document
D 7: The properties that we pass to the User constructor don't necessarily match up with the properties available on a user
That is why we create UserDoc(Check at the end for code)
A little trick while creating new User
Any time we want to create a new User, we will call buildUser
We are creating this function for Typescript to get involved
Add a new method to the User model
userSchema.statics.build=(attrs: UserAttrs)=>{returnnewUser(attrs);};// this is how we add a custom function built into a model//But when we try to use User.build() we still get this errorProperty'build'doesnotexistontype'Model<Document>'
To fix it we create UserModel interface
What's that Angle Bracket For?
Angular brackets are for generic syntax
You can think them as functions of types
When we call model with parenthesis
UserDoc and UserModel can be seen as arguments to model
They are types being provided to the function
Command click on model to understand better
UserModel is the return type of model
// User model fileimportmongoosefrom'mongoose';import{Password}from'../services/password';// An interface that describes the properties// that are required to create a new UserinterfaceUserAttrs{email: string;password: string;}// An interface that describes the properties // that a User Model hasinterfaceUserModelextendsmongoose.Model<UserDoc>{build(attrs: UserAttrs): UserDoc;}// An interface that describes the properties// that a User Document hasinterfaceUserDocextendsmongoose.Document{email: string;password: string;}constuserSchema=newmongoose.Schema({email: {type: String,required: true,},password: {type: String,required: true,},},{toJSON: {transform(doc,ret){ret.id=ret._id;deleteret._id;deleteret.password;deleteret.__v;}}});userSchema.pre('save',asyncfunction(done){if(this.isModified('password')){consthashed=awaitPassword.toHash(this.get('password'));this.set('password',hashed);}done();})userSchema.statics.build=(attrs: UserAttrs)=>{returnnewUser(attrs);};constUser=mongoose.model<UserDoc,UserModel>('User',userSchema);export{User};