Configure TypeORM and Database Connection
Explore how to configure TypeORM in a NestJS application, establish a connection to a MySQL database, and securely manage database credentials using environment variables. Learn to handle multiple runtime environments and set up automatic or manual schema synchronization to maintain your database structure effectively.
Set up TypeORM in NestJS
In this lesson, we’ll delve into TypeORM configuration and establish a database connection in the NestJS app. We’ll also explore how to manage and store database settings in different environments securely.
Install the dependencies
First, we must install the dependencies.
npm install typeorm @nestjs/typeorm mysql
The packages are given below:
typeorm: This is the main package for TypeORM.@nestjs/typeorm: This is a package for the integration of TypeORM with NestJS.mysql: This is a package that provides a JavaScript API for connecting, querying, and managing MySQL databases.
Create the database
Then, we create a new database in the MySQL database using the following SQL scripts. Note that the database is already provisioned in the live code editor. Therefore, the script is for reference.
TypeORM configuration
To integrate TypeORM into the app, we need to add the following code to AppModule:
Here, we use the TypeOrmModule.forRoot method to set up the configuration for TypeORM. ...