Mongoose Models with TypeScript
August 31, 2021
I learned this idea from a Stephen Grider course.
Mongoose comes with its own type system that checks types when interacting with MongoDB but this does not allow attributes being passed to the Model to be checked with TypeScript.
The first thing that needs to be added is an interface that has the attributes you will be passing into the Model.
This is used with a static method that we add to the model that allows us to put constraints on the input. It's just a wrapper that adds types to the attributes before passing them into the model.
Next, we need an interface that includes the new static method that we added.
We need one last interface that defines the Document. This is used in the interface above and when creating the Schema.
Now we build the Schema with Mongoose types and use the PersonDoc interface.
Finally, we create a Model object using both interfaces and export it.
Now you use the build method when using the model and types will be checked.
The full example