node.jsnestjstypeormentities

Are entities required for a NestJS backend?


NestJS encourages the use of TypeORM and entities to interact with database. I have experience with Express, but NestJS, TypeORM and their entities concepts are new to me.

Previously, when I worked with Express back end, I have been using raw SQL statements (and with command line in some cases) to interact with the database (from CRUD to database deployment). NestJS can also connect to an existing database (says, PostgreSQL in this case) without using entities (completely delete entities directory).

With that said, why do we need entities? Is it necessary for a NestJS backend when I'm familiar with raw SQL? And what's a good practice for working with database in NestJS?


Solution

  • Do we need entities?

    Nope. Not at all. You can write raw SQL with pg or any other package all you want. It's actually what I do here

    Why do we need entities?

    It really depends on how you're managing your database schema, in my opinion. If you're letting TypeO/Mikro/prisma manage the schema for you, then entities are useful. If you're using something like Hasura, then the migrations are written in SQL and Hasura generates the types for you (I think prisma might be similar here actually).

    Personally, what I prefer doing is making my own mini-orm that deserializes and validates the data from the database before passing it back on to the client. I can write raw SQL this way, and map it to my defined types, rather than relying than on a full ORM.