zuloosolution.blogg.se

Nodejs typescript
Nodejs typescript






The first generic type UserDocument ensures that when we call the functions such as findById(), we can get the correct return type instead of Document. Lastly, to construct a Mongoose model to be exported, we pass in UserDocument(default return type) and UserModel as the two generic types: export default model ("User", UserSchema) If any query returns a populated result, we can simply create a static method and define its return type, see findM圜ompany: it returns a populated user object, so its return type is UserPopulatedDocument Final model creation Thus, UserDocument is passed in instead of UserPopulatedDocument. The generic type is used as the default return type for the query results. For this, we created a new type UserModel which extends Model from Mongoose with a generic type UserDocument. Īfter the instance methods, we have static methods for Mongoose Model. The nested schema interface DOES NOT inherent from Document. Some schema may have nested document, the way to type a nested document is a little bit different from the top level schema. Similarly, for the creditCard field, we used the Map type supported by Mongoose Types.Map for better typing. friends?: Types.Array) is because by default Mongoose will initialize array type field to be an empty array. Note: here we didn’t use the optional mark “ ?” (e.g. This is because by using the Mongoose provided type Array, we will be able to call some Mongoose specific methods on it such as addToSet() which is not available in normal ES Array type. įor the friends and creditCards field, they have been overwritten by the types provided by Mongoose.

nodejs typescript

This interface is created so that it can be used to for document creation such as the following code: import UserModel. This will be overwritten later on with the document interfaces all the types are ES types instead of Mongoose types except for the reference field company.Now, I will explain piece by piece: Schema and Documentįirst, we create an interface named User just to reflect the UserSchema we defined back in the JavaScript file.








Nodejs typescript