A Simple Guide to CRUD Operations with TypeORM
A Simple Guide to CRUD Operations with TypeORM
TypeORM is a popular and powerful Object Relational Mapper (ORM) library that runs on Node.js. It is highly preferred especially in TypeScript projects because of its compatibility with various databases (PostgreSQL, MySQL, SQLite, etc.) and its easy installation. In this article, we will learn step by step how to perform basic CRUD (Create, Read, Update, Delete) operations using TypeORM. With Simple CRUD Operations with TypeORM you can easily manage data in your application.
TypeORM Installation and Creating an Entity
To start, we first need to add TypeORM and the necessary packages to our project. You can do the basic setups with the following command:
npm install typeorm reflect-metadata sqlite3Now let’s define a simple User entity:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
}
CRUD Operations: Simple Examples
Creating a User (Create)
import { AppDataSource } from "./data-source";
import { User } from "./entity/User";
const userRepository = AppDataSource.getRepository(User);
// Adding a user
const user = new User();
user.name = "Ahmet";
user.email = "ahmet@example.com";
await userRepository.save(user);
Listing Users (Read)
// Fetch all users
const users = await userRepository.find();
console.log(users);
Updating a User (Update)
// Update a user
const userToUpdate = await userRepository.findOneBy({ id: 1 });
if (userToUpdate) {
userToUpdate.name = "Mehmet";
await userRepository.save(userToUpdate);
}
Deleting a User (Delete)
// Delete a user
await userRepository.delete({ id: 1 });
Conclusion
Performing simple CRUD operations with TypeORM is easy and practical. Strongly integrated with TypeScript, TypeORM makes database management quite accessible for developers. By using our guide on Simple CRUD Operations with TypeORM, you too can quickly add data management functions to your projects. For more features and advanced topics, we recommend checking out the TypeORM documentation.


Yorum Gönder