DEV Community

ayka.code
ayka.code

Posted on

Using TypeORM with PostgreSQL in a Node.js and Express Application

In this tutorial, we will learn how to use TypeORM with a PostgreSQL database in a Node.js and Express application. TypeORM is an ORM (Object-Relational Mapper) that can be used with several different database management systems, including PostgreSQL. It simplifies the process of working with databases by providing a set of classes and methods that can be used to perform common database operations, such as querying and inserting data.

Prerequisites:

  • Node.js and npm installed on your system
  • A PostgreSQL database set up and running
  • Basic knowledge of Node.js and Express
  • Knowledge on how to setup a Node.js project with Typescript (just install typescript as a global package and run tsc --init)

Step 1: Create a new Node.js and Express project

Create a new directory for your project and navigate to it in your terminal. Then, run the following command to create a new Node.js project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create a package.json file in your project directory. Next, install the express and typeorm packages by running the following command:

npm install express typeorm
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up a TypeORM configuration file

TypeORM uses a configuration file to connect to the database and define your models. Create a new file in your project directory called ormconfig.json and add the following code to it:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "YOUR_USERNAME",
  "password": "YOUR_PASSWORD",
  "database": "YOUR_DATABASE_NAME",
  "entities": ["src/entity/*.ts"],
  "synchronize": true
}
Enter fullscreen mode Exit fullscreen mode

Replace the placeholder values with your own database connection details. The "entities" property specifies the location of your model files, and the "synchronize" property tells TypeORM to synchronize your models with the database schema.

Step 3: Define your models

Next, you will need to define your models. These are classes that represent the entities in your database, such as users or products. Create a new directory called "entity" in the "src" directory and add a new file called "user.ts" to it. Then, add the following code to define a simple User model:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;

  @Column()
  password: string;
}
Enter fullscreen mode Exit fullscreen mode

This model has three properties: an id field that is the primary key and is auto-incremented, a username field, and a password field.

Step 4: Set up the Express server

Now, you can set up the Express server. Create a new file called "server.ts" in the "src" directory and add the following code to it:

import express from 'express';
import { createConnection } from 'typeorm';

const app = express();

createConnection()
  .then(() => {
    console.log('Connected to database');
  })
  .catch((error) => {
    console.log('Error connecting to database:', error);
  });

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

This code creates an Express server, establishes a connection to the database using the TypeORM createConnection() function, and sets up a simple route that sends a "Hello, world!" message when the root URL is accessed.

Step 5: Query the database

Now that you have your models and Express server set up, you can start querying the database. To do this, you can use the EntityManager class provided by TypeORM. Add the following code to the "server.ts" file to create a new user and save it to the database:

import { EntityManager } from 'typeorm';
import { User } from './entity/user';

app.post('/users', async (req, res) => {
  const entityManager = req.container.get(EntityManager);
  const user = new User();
  user.username = 'john';
  user.password = 'password';
  await entityManager.save(user);
  res.send('User saved');
});
Enter fullscreen mode Exit fullscreen mode

This code creates a new user object, sets its properties, and saves it to the database using the EntityManager's save() method.

Step 6: Test the application

To test the application, start the server by running the following command:

node dist/server.js
Enter fullscreen mode Exit fullscreen mode

Then, open a web browser and navigate to http://localhost:3000. You should see the "Hello, world!" message displayed. To test the database functionality, send a POST request to http://localhost:3000/users using a tool such as Postman or cURL. This should create a new user in the database.

Conclusion:

In this tutorial, we learned how to use TypeORM with a PostgreSQL database in a Node.js and Express application. TypeORM simplifies the process of working with databases and provides a set of useful features such as object-relational mapping and a powerful query builder. With TypeORM, you can easily build robust and scalable web applications with Node.js and Express.

At the end of this blog post, I want to thank all of my readers for following along and for their support. I'm grateful for the opportunity to share my knowledge and experiences with you, and I hope that my posts have been helpful and informative.

I'm always looking for ways to improve and grow, so please don't hesitate to leave comments or feedback on my posts. I appreciate your input and value your opinions.

Finally, don't forget to follow me on Twitter for updates on new blog posts and other interesting content. Thanks again for your support and I look forward to continuing to share my knowledge with you.

Top comments (2)

Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Thanks for putting the time to share this short and clear post Ayka! 👌

Collapse
 
mateusmrosa profile image
Mateus Martinez rosa • Edited

Is it possible to work in the same way, but with a .js extension? Removing an type?