Design Better Database Models
Learn how to design better models when using MongoDB as a database in your application.
Below are some key points to design better database models:
- We always use the correct data type for the field. For example, numbers should not be stored as a string, they should be of int, long, decimal, or double type only.
- Field names should have a consistent naming approach. For example, they should either be in camelCase or use an underscore (
_
) between two or more words. - MongoDB offers great flexibility to design models using embedded models. If possible, we should always convert the information of an entity into objects and embed it into the primary model. As a result, the information representation becomes very good.
- Normalization should be considered when we don’t have a good benefit of embedding. In that case, the embedded document is used in multiple collections.
- We keep our collection schema consistent for all the records. We don’t skip fields in records and avoid additional handling on the query level.
- Indexing is important. We find out which fields need indexing and apply it to them. We should avoid unnecessary indexing because it may cause performance issues on write operations.
- We use GridFS to store large files instead of binary Data.
- We should prefer the
Date
type for dates instead of storing them intonumbers
. - Fields like a
Birthdate
should be of typeDate
, and should not store any time value. - We store the currency, and use the
Amount
field to store the lowest value of the currency.
Get hands-on with 1200+ tech skills courses.