Object Mapping
Utilize the power of TypeScript classes in your models
What is a model
Let's suppose we have this basic structure for our document
Out of the above document we can guess few things that aren't mentioned directly in document, like:
The current age of Alex Covri
His first name
His last name
How long he has been into web development
Whether he knows some backend
Whether he knows some frontend
Whether he is a full stack developer
And we can translate those guesses into a `get` methods in a class, like this:
The class above is called a Model.
In the class above, for any developer we can guess 9 properties out of 3 properties (a total of 12 properties). Also, we've written some methods that helps us in the editing of the developer properties. The possibilities are endless!
Using new
method
new
methodAnd since we're extending BaseModel
we're also aided by a method called new
which can help us create a new developer in a one liner
Persisting and Mapping
When persisting data, the model will not be persisted, only the actual fields (neither getters nor methods) will be persisted.
Querying and updating
You can query documents based on the getter properties like this
but you can not update getter properties nor methods, and it would result in unexpected behaviors.
Best practices
Define computed getters instead of functions and methods.
Always use
Model.new
to create new documents.Use computed properties (getter methods) for querying.
Define
createdAt
andupdatedAt
in your model when you're using them in you database.Never try to directly set a computed property or update it via the update operators.
Use
Model.new
in conjugation with the upsert operator$setOnInsert
.Write computed properties (getter methods) to simplify your queries.
Always defined defaults for your fields in the model.
As the database is actually a class you can also extends this class before calling it, adding your own methods and keeping your code cleanly OOP.
Last updated