📜  typeorm find with limit - TypeScript (1)

📅  最后修改于: 2023-12-03 15:05:39.137000             🧑  作者: Mango

TypeORM Find with Limit - TypeScript

TypeORM is an Object-Relational Mapping (ORM) library for TypeScript and JavaScript that allows developers to interact with a database using an object-oriented approach. One of the most common tasks when working with databases is retrieving data using a query. TypeORM provides the find method to query the database and retrieve data. In this tutorial, we will explore how to use the find method with a limit to retrieve a specific number of records.

Prerequisites

To follow this tutorial, you need to have the following installed on your machine:

  • Node.js and NPM
  • TypeScript
  • TypeORM
  • A database (we will use PostgreSQL)
Getting Started

Let's begin by creating a new TypeScript project. Open your terminal and run the following commands:

mkdir typeorm-find-with-limit
cd typeorm-find-with-limit
npm init -y

Next, install the necessary dependencies:

npm install typeorm pg reflect-metadata @types/pg @types/node --save-dev

Create a new file called index.ts and add the following code:

import "reflect-metadata";
import { createConnection } from "typeorm";
import { User } from "./entity/User";

createConnection()
  .then(async (connection) => {
    const users = await connection.manager.find(User, { take: 5 });

    console.log(users);
  })
  .catch((error) => console.log(error));

In this code, we import the createConnection method from TypeORM, which connects to the database. We also import the User entity from a file called User.ts. In the createConnection method, we use the manager.find method to retrieve the first five users from the database.

Next, let's create the User entity. Create a new file called User.ts and add the following code:

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

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

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  age: number;
}

In this code, we define the User entity, which has four fields: id, firstName, lastName, and age. The @PrimaryGeneratedColumn decorator indicates that the id field is the primary key. The @Column decorator indicates that the field should be mapped to a database column.

Now, let's create a database and table to store our User entities. We will use PostgreSQL for this tutorial. Open your terminal and run the following commands:

docker run --name postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres
docker exec -it postgres bash
psql -U postgres
CREATE DATABASE mydatabase;
\q
psql -U postgres -d mydatabase
CREATE TABLE user (id SERIAL PRIMARY KEY, "firstName" VARCHAR(255), "lastName" VARCHAR(255), age INT);

In this code, we start a PostgreSQL container and connect to it using the psql command. We create a new database called mydatabase and a table called user, which has the same fields as our User entity.

Next, let's build and run our application. Run the following command:

tsc index.ts && node index.js

This will compile our TypeScript code to JavaScript and run the index.js file. You should see the first five users logged to the console.

Using Limit

Now that we have retrieved the first five users, let's retrieve a specific number of users using the limit option. Modify the index.ts file as follows:

import "reflect-metadata";
import { createConnection } from "typeorm";
import { User } from "./entity/User";

createConnection()
  .then(async (connection) => {
    const users = await connection.manager.find(User, { take: 5, skip: 5 });

    console.log(users);
  })
  .catch((error) => console.log(error));

In this modified code, we use the take option to retrieve only five users and the skip option to skip the first five users and retrieve the next five users. Consequently, we're getting an additional five users that follow the first five.

Let's build and run our application again:

tsc index.ts && node index.js

You should see the next five users logged to the console.

Conclusion

In this tutorial, we've learned how to use the TypeORM find method with a limit to retrieve a specific number of records from a database in TypeScript. We've also explored how to create a simple User entity and a table to store our User entities. Use this approach to interact with your database in a clean, object-oriented way. Happy coding!