ORM and NestJS

Get an introduction to ORM and understand how NestJS works with ORM.

ORM

ORM stands for object-relational mapping. It’s a technique to interact with relational databases using objects and classes rather than writing raw SQL queries.

In this lesson, we’ll explore ORM’s fundamentals and benefits, including how it simplifies database interactions and enhances application maintainability. We’ll also learn how NestJS seamlessly integrates with ORM, allowing us to work with databases in a structured and efficient manner.

How it works

ORM creates a bridge between the objects in our code and the tables in the database. It maps objects and classes to database tables through “object-relational mapping.”

Here’s a simplified explanation of how this mapping works:

  • Entities: We define entities as classes. Each class represents a specific data model, like User.

  • Properties and decorators: We define properties corresponding to a database table’s columns within the entity classes. For example, a User class might have properties like name, email, and password. We use decorators to specify the mapping between the properties and the database table columns. These annotations indicate which property is associated with which column in the table.

  • Model configuration: We often configure the entity or class further, specifying details like the table name, primary key, and relationships with other entities. This configuration helps ORM understand how to interact with the database.

  • SQL query generation: When performing operations on these entities in the code—for example, querying or saving—ORM generates SQL queries based on requested object-oriented operations.

  • Database operations: ORM sends these generated SQL queries to the database for execution. The database stores and retrieves data according to the instructions in these queries.

  • Data mapping: When retrieved from the database, ORM maps the result to the corresponding entities or objects.

Get hands-on with 1400+ tech skills courses.