ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
Installations
npm install typeorm
Score
66.8
Supply Chain
85.6
Quality
87.3
Maintenance
25
Vulnerability
89.6
License
Developer
Developer Guide
Module System
CommonJS, ESM, UMD
Min. Node Version
>=16.13.0
Typescript Support
Yes
Node Version
18.18.2
NPM Version
9.8.1
Statistics
34,406 Stars
5,389 Commits
6,332 Forks
348 Watching
5 Branches
1,056 Contributors
Updated on 29 Nov 2024
Bundle Size
625.03 kB
Minified
133.17 kB
Minified + Gzipped
Languages
TypeScript (99.83%)
JavaScript (0.17%)
Total Downloads
Cumulative downloads
Total Downloads
267,170,520
Last day
-17.8%
354,660
Compared to previous day
Last week
-4.7%
2,171,305
Compared to previous week
Last month
7.3%
9,384,623
Compared to previous month
Last year
33.1%
90,697,394
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
15
Peer Dependencies
17
Dev Dependencies
53
TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES2021). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large-scale enterprise applications with multiple databases.
TypeORM supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high-quality, loosely coupled, scalable, maintainable applications in the most productive way.
TypeORM is highly influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.
📣 Announcement: The Future of TypeORM
We’re excited to share our vision for a revitalized TypeORM—a strategy focused on building a stable, robust, and sustainable foundation for the long term. Learn how we’re structuring maintenance and bringing together dedicated resources to ensure TypeORM thrives for years to come.
Features
- Supports both DataMapper and ActiveRecord (your choice).
- Entities and columns.
- Database-specific column types.
- Entity manager.
- Repositories and custom repositories.
- Clean object-relational model.
- Associations (relations).
- Eager and lazy relations.
- Uni-directional, bi-directional, and self-referenced relations.
- Supports multiple inheritance patterns.
- Cascades.
- Indices.
- Transactions.
- Migrations and automatic migrations generation.
- Connection pooling.
- Replication.
- Using multiple database instances.
- Working with multiple database types.
- Cross-database and cross-schema queries.
- Elegant-syntax, flexible and powerful QueryBuilder.
- Left and inner joins.
- Proper pagination for queries using joins.
- Query caching.
- Streaming raw results.
- Logging.
- Listeners and subscribers (hooks).
- Supports closure table pattern.
- Schema declaration in models or separate configuration files.
- Supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js.
- Supports MongoDB NoSQL database.
- Works in NodeJS / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
- TypeScript and JavaScript support.
- ESM and CommonJS support.
- Produced code is performant, flexible, clean, and maintainable.
- Follows all possible best practices.
- CLI.
And more...
With TypeORM your models look like this:
1import { Entity, PrimaryGeneratedColumn, Column } from "typeorm" 2 3@Entity() 4export class User { 5 @PrimaryGeneratedColumn() 6 id: number 7 8 @Column() 9 firstName: string 10 11 @Column() 12 lastName: string 13 14 @Column() 15 age: number 16}
And your domain logic looks like this:
1const userRepository = MyDataSource.getRepository(User) 2 3const user = new User() 4user.firstName = "Timber" 5user.lastName = "Saw" 6user.age = 25 7await userRepository.save(user) 8 9const allUsers = await userRepository.find() 10const firstUser = await userRepository.findOneBy({ 11 id: 1, 12}) // find by id 13const timber = await userRepository.findOneBy({ 14 firstName: "Timber", 15 lastName: "Saw", 16}) // find by firstName and lastName 17 18await userRepository.remove(timber)
Alternatively, if you prefer to use the ActiveRecord
implementation, you can use it as well:
1import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm" 2 3@Entity() 4export class User extends BaseEntity { 5 @PrimaryGeneratedColumn() 6 id: number 7 8 @Column() 9 firstName: string 10 11 @Column() 12 lastName: string 13 14 @Column() 15 age: number 16}
And your domain logic will look this way:
1const user = new User() 2user.firstName = "Timber" 3user.lastName = "Saw" 4user.age = 25 5await user.save() 6 7const allUsers = await User.find() 8const firstUser = await User.findOneBy({ 9 id: 1, 10}) 11const timber = await User.findOneBy({ 12 firstName: "Timber", 13 lastName: "Saw" 14}) 15 16await timber.remove()
Installation
-
Install the npm package:
npm install typeorm --save
-
You need to install
reflect-metadata
shim:npm install reflect-metadata --save
and import it somewhere in the global place of your app (for example in
app.ts
):import "reflect-metadata"
-
You may need to install node typings:
npm install @types/node --save-dev
-
Install a database driver:
-
for MySQL or MariaDB
npm install mysql --save
(you can installmysql2
instead as well) -
for PostgreSQL or CockroachDB
npm install pg --save
-
for SQLite
npm install sqlite3 --save
-
for Microsoft SQL Server
npm install mssql --save
-
for sql.js
npm install sql.js --save
-
for Oracle
npm install oracledb --save
To make the Oracle driver work, you need to follow the installation instructions from their site.
-
for SAP Hana
npm install @sap/hana-client npm install hdb-pool
SAP Hana support made possible by the sponsorship of Neptune Software.
-
for Google Cloud Spanner
npm install @google-cloud/spanner --save
Provide authentication credentials to your application code by setting the environment variable
GOOGLE_APPLICATION_CREDENTIALS
:1# Linux/macOS 2export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH" 3 4# Windows 5set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH 6 7# Replace KEY_PATH with the path of the JSON file that contains your service account key.
To use Spanner with the emulator you should set
SPANNER_EMULATOR_HOST
environment variable:1# Linux/macOS 2export SPANNER_EMULATOR_HOST=localhost:9010 3 4# Windows 5set SPANNER_EMULATOR_HOST=localhost:9010
-
for MongoDB (experimental)
npm install mongodb@^5.2.0 --save
-
for NativeScript, react-native and Cordova
Install only one of them, depending on which database you use.
-
TypeScript configuration
Also, make sure you are using TypeScript version 4.5 or higher,
and you have enabled the following settings in tsconfig.json
:
1"emitDecoratorMetadata": true, 2"experimentalDecorators": true,
You may also need to enable es6
in the lib
section of compiler options, or install es6-shim
from @types
.
Quick Start
The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project. Quick start works only if you are using TypeORM in a NodeJS application. If you are using other platforms, proceed to the step-by-step guide.
To create a new project using CLI, run the following command:
1npx typeorm init --name MyProject --database postgres
Where name
is the name of your project and database
is the database you'll use.
Database can be one of the following values: mysql
, mariadb
, postgres
, cockroachdb
, sqlite
, mssql
, sap
, spanner
, oracle
, mongodb
,
cordova
, react-native
, expo
, nativescript
.
This command will generate a new project in the MyProject
directory with the following files:
MyProject
├── src // place of your TypeScript code
│ ├── entity // place where your entities (database models) are stored
│ │ └── User.ts // sample entity
│ ├── migration // place where your migrations are stored
│ ├── data-source.ts // data source and all connection configuration
│ └── index.ts // start point of your application
├── .gitignore // standard gitignore file
├── package.json // node module dependencies
├── README.md // simple readme file
└── tsconfig.json // TypeScript compiler options
You can also run
typeorm init
on an existing node project, but be careful - it may override some files you already have.
The next step is to install new project dependencies:
1cd MyProject 2npm install
After you have all dependencies installed, edit the data-source.ts
file and put your own database connection configuration options in there:
1export const AppDataSource = new DataSource({ 2 type: "postgres", 3 host: "localhost", 4 port: 5432, 5 username: "test", 6 password: "test", 7 database: "test", 8 synchronize: true, 9 logging: true, 10 entities: [Post, Category], 11 subscribers: [], 12 migrations: [], 13})
Particularly, most of the time you'll only need to configure
host
, username
, password
, database
and maybe port
options.
Once you finish with configuration and all node modules are installed, you can run your application:
1npm start
That's it, your application should successfully run and insert a new user into the database. You can continue to work with this project and integrate other modules you need and start creating more entities.
You can generate an ESM project by running
npx typeorm init --name MyProject --database postgres --module esm
command.
You can generate an even more advanced project with express installed by running
npx typeorm init --name MyProject --database mysql --express
command.
You can generate a docker-compose file by running
npx typeorm init --name MyProject --database postgres --docker
command.
Step-by-Step Guide
What are you expecting from ORM? First of all, you are expecting it will create database tables for you and find / insert / update / delete your data without the pain of having to write lots of hardly maintainable SQL queries. This guide will show you how to set up TypeORM from scratch and make it do what you are expecting from an ORM.
Create a model
Working with a database starts with creating tables. How do you tell TypeORM to create a database table? The answer is - through the models. Your models in your app are your database tables.
For example, you have a Photo
model:
1export class Photo { 2 id: number 3 name: string 4 description: string 5 filename: string 6 views: number 7 isPublished: boolean 8}
And you want to store photos in your database. To store things in the database, first, you need a database table, and database tables are created from your models. Not all models, but only those you define as entities.
Create an entity
Entity is your model decorated by an @Entity
decorator.
A database table will be created for such models.
You work with entities everywhere in TypeORM.
You can load/insert/update/remove and perform other operations with them.
Let's make our Photo
model an entity:
1import { Entity } from "typeorm" 2 3@Entity() 4export class Photo { 5 id: number 6 name: string 7 description: string 8 filename: string 9 views: number 10 isPublished: boolean 11}
Now, a database table will be created for the Photo
entity and we'll be able to work with it anywhere in our app.
We have created a database table, however, what table can exist without columns?
Let's create a few columns in our database table.
Adding table columns
To add database columns, you simply need to decorate an entity's properties you want to make into a column
with a @Column
decorator.
1import { Entity, Column } from "typeorm" 2 3@Entity() 4export class Photo { 5 @Column() 6 id: number 7 8 @Column() 9 name: string 10 11 @Column() 12 description: string 13 14 @Column() 15 filename: string 16 17 @Column() 18 views: number 19 20 @Column() 21 isPublished: boolean 22}
Now id
, name
, description
, filename
, views
, and isPublished
columns will be added to the photo
table.
Column types in the database are inferred from the property types you used, e.g.
number
will be converted into integer
, string
into varchar
, boolean
into bool
, etc.
But you can use any column type your database supports by explicitly specifying a column type into the @Column
decorator.
We generated a database table with columns, but there is one thing left. Each database table must have a column with a primary key.
Creating a primary column
Each entity must have at least one primary key column.
This is a requirement and you can't avoid it.
To make a column a primary key, you need to use the @PrimaryColumn
decorator.
1import { Entity, Column, PrimaryColumn } from "typeorm" 2 3@Entity() 4export class Photo { 5 @PrimaryColumn() 6 id: number 7 8 @Column() 9 name: string 10 11 @Column() 12 description: string 13 14 @Column() 15 filename: string 16 17 @Column() 18 views: number 19 20 @Column() 21 isPublished: boolean 22}
Creating an auto-generated column
Now, let's say you want your id column to be auto-generated (this is known as auto-increment / sequence / serial / generated identity column).
To do that, you need to change the @PrimaryColumn
decorator to a @PrimaryGeneratedColumn
decorator:
1import { Entity, Column, PrimaryGeneratedColumn } from "typeorm" 2 3@Entity() 4export class Photo { 5 @PrimaryGeneratedColumn() 6 id: number 7 8 @Column() 9 name: string 10 11 @Column() 12 description: string 13 14 @Column() 15 filename: string 16 17 @Column() 18 views: number 19 20 @Column() 21 isPublished: boolean 22}
Column data types
Next, let's fix our data types. By default, the string is mapped to a varchar(255)-like type (depending on the database type). The number is mapped to an integer-like type (depending on the database type). We don't want all our columns to be limited varchars or integers. Let's setup the correct data types:
1import { Entity, Column, PrimaryGeneratedColumn } from "typeorm" 2 3@Entity() 4export class Photo { 5 @PrimaryGeneratedColumn() 6 id: number 7 8 @Column({ 9 length: 100, 10 }) 11 name: string 12 13 @Column("text") 14 description: string 15 16 @Column() 17 filename: string 18 19 @Column("double") 20 views: number 21 22 @Column() 23 isPublished: boolean 24}
Column types are database-specific. You can set any column type your database supports. More information on supported column types can be found here.
Creating a new DataSource
Now, when our entity is created, let's create index.ts
file and set up our DataSource
there:
1import "reflect-metadata" 2import { DataSource } from "typeorm" 3import { Photo } from "./entity/Photo" 4 5const AppDataSource = new DataSource({ 6 type: "postgres", 7 host: "localhost", 8 port: 5432, 9 username: "root", 10 password: "admin", 11 database: "test", 12 entities: [Photo], 13 synchronize: true, 14 logging: false, 15}) 16 17// to initialize the initial connection with the database, register all entities 18// and "synchronize" database schema, call "initialize()" method of a newly created database 19// once in your application bootstrap 20AppDataSource.initialize() 21 .then(() => { 22 // here you can start to work with your database 23 }) 24 .catch((error) => console.log(error))
We are using Postgres in this example, but you can use any other supported database.
To use another database, simply change the type
in the options to the database type you are using:
mysql
, mariadb
, postgres
, cockroachdb
, sqlite
, mssql
, oracle
, sap
, spanner
, cordova
, nativescript
, react-native
,
expo
, or mongodb
.
Also make sure to use your own host, port, username, password, and database settings.
We added our Photo entity to the list of entities for this data source. Each entity you are using in your connection must be listed there.
Setting synchronize
makes sure your entities will be synced with the database, every time you run the application.
Running the application
Now if you run your index.ts
, a connection with the database will be initialized and a database table for your photos will be created.
1+-------------+--------------+----------------------------+ 2| photo | 3+-------------+--------------+----------------------------+ 4| id | int(11) | PRIMARY KEY AUTO_INCREMENT | 5| name | varchar(100) | | 6| description | text | | 7| filename | varchar(255) | | 8| views | int(11) | | 9| isPublished | boolean | | 10+-------------+--------------+----------------------------+
Creating and inserting a photo into the database
Now let's create a new photo to save it in the database:
1import { Photo } from "./entity/Photo" 2import { AppDataSource } from "./index" 3 4const photo = new Photo() 5photo.name = "Me and Bears" 6photo.description = "I am near polar bears" 7photo.filename = "photo-with-bears.jpg" 8photo.views = 1 9photo.isPublished = true 10 11await AppDataSource.manager.save(photo) 12console.log("Photo has been saved. Photo id is", photo.id)
Once your entity is saved it will get a newly generated id.
save
method returns an instance of the same object you pass to it.
It's not a new copy of the object, it modifies its "id" and returns it.
Using Entity Manager
We just created a new photo and saved it in the database.
We used EntityManager
to save it.
Using entity manager you can manipulate any entity in your app.
For example, let's load our saved entity:
1import { Photo } from "./entity/Photo" 2import { AppDataSource } from "./index" 3 4const savedPhotos = await AppDataSource.manager.find(Photo) 5console.log("All photos from the db: ", savedPhotos)
savedPhotos
will be an array of Photo objects with the data loaded from the database.
Learn more about EntityManager here.
Using Repositories
Now let's refactor our code and use Repository
instead of EntityManager
.
Each entity has its own repository which handles all operations with its entity.
When you deal with entities a lot, Repositories are more convenient to use than EntityManagers:
1import { Photo } from "./entity/Photo" 2import { AppDataSource } from "./index" 3 4const photo = new Photo() 5photo.name = "Me and Bears" 6photo.description = "I am near polar bears" 7photo.filename = "photo-with-bears.jpg" 8photo.views = 1 9photo.isPublished = true 10 11const photoRepository = AppDataSource.getRepository(Photo) 12 13await photoRepository.save(photo) 14console.log("Photo has been saved") 15 16const savedPhotos = await photoRepository.find() 17console.log("All photos from the db: ", savedPhotos)
Learn more about Repository here.
Loading from the database
Let's try more load operations using the Repository:
1import { Photo } from "./entity/Photo" 2import { AppDataSource } from "./index" 3 4const photoRepository = AppDataSource.getRepository(Photo) 5const allPhotos = await photoRepository.find() 6console.log("All photos from the db: ", allPhotos) 7 8const firstPhoto = await photoRepository.findOneBy({ 9 id: 1, 10}) 11console.log("First photo from the db: ", firstPhoto) 12 13const meAndBearsPhoto = await photoRepository.findOneBy({ 14 name: "Me and Bears", 15}) 16console.log("Me and Bears photo from the db: ", meAndBearsPhoto) 17 18const allViewedPhotos = await photoRepository.findBy({ views: 1 }) 19console.log("All viewed photos: ", allViewedPhotos) 20 21const allPublishedPhotos = await photoRepository.findBy({ isPublished: true }) 22console.log("All published photos: ", allPublishedPhotos) 23 24const [photos, photosCount] = await photoRepository.findAndCount() 25console.log("All photos: ", photos) 26console.log("Photos count: ", photosCount)
Updating in the database
Now let's load a single photo from the database, update it and save it:
1import { Photo } from "./entity/Photo" 2import { AppDataSource } from "./index" 3 4const photoRepository = AppDataSource.getRepository(Photo) 5const photoToUpdate = await photoRepository.findOneBy({ 6 id: 1, 7}) 8photoToUpdate.name = "Me, my friends and polar bears" 9await photoRepository.save(photoToUpdate)
Now photo with id = 1
will be updated in the database.
Removing from the database
Now let's remove our photo from the database:
1import { Photo } from "./entity/Photo" 2import { AppDataSource } from "./index" 3 4const photoRepository = AppDataSource.getRepository(Photo) 5const photoToRemove = await photoRepository.findOneBy({ 6 id: 1, 7}) 8await photoRepository.remove(photoToRemove)
Now photo with id = 1
will be removed from the database.
Creating a one-to-one relation
Let's create a one-to-one relationship with another class.
Let's create a new class in PhotoMetadata.ts
. This PhotoMetadata class is supposed to contain our photo's additional meta-information:
1import { 2 Entity, 3 Column, 4 PrimaryGeneratedColumn, 5 OneToOne, 6 JoinColumn, 7} from "typeorm" 8import { Photo } from "./Photo" 9 10@Entity() 11export class PhotoMetadata { 12 @PrimaryGeneratedColumn() 13 id: number 14 15 @Column("int") 16 height: number 17 18 @Column("int") 19 width: number 20 21 @Column() 22 orientation: string 23 24 @Column() 25 compressed: boolean 26 27 @Column() 28 comment: string 29 30 @OneToOne(() => Photo) 31 @JoinColumn() 32 photo: Photo 33}
Here, we are using a new decorator called @OneToOne
. It allows us to create a one-to-one relationship between two entities.
type => Photo
is a function that returns the class of the entity with which we want to make our relationship.
We are forced to use a function that returns a class, instead of using the class directly, because of the language specifics.
We can also write it as () => Photo
, but we use type => Photo
as a convention to increase code readability.
The type variable itself does not contain anything.
We also add a @JoinColumn
decorator, which indicates that this side of the relationship will own the relationship.
Relations can be unidirectional or bidirectional.
Only one side of relational can be owning.
Using @JoinColumn
decorator is required on the owner side of the relationship.
If you run the app, you'll see a newly generated table, and it will contain a column with a foreign key for the photo relation:
1+-------------+--------------+----------------------------+ 2| photo_metadata | 3+-------------+--------------+----------------------------+ 4| id | int(11) | PRIMARY KEY AUTO_INCREMENT | 5| height | int(11) | | 6| width | int(11) | | 7| comment | varchar(255) | | 8| compressed | boolean | | 9| orientation | varchar(255) | | 10| photoId | int(11) | FOREIGN KEY | 11+-------------+--------------+----------------------------+
Save a one-to-one relation
Now let's save a photo, and its metadata and attach them to each other.
1import { Photo } from "./entity/Photo" 2import { PhotoMetadata } from "./entity/PhotoMetadata" 3 4// create a photo 5const photo = new Photo() 6photo.name = "Me and Bears" 7photo.description = "I am near polar bears" 8photo.filename = "photo-with-bears.jpg" 9photo.views = 1 10photo.isPublished = true 11 12// create a photo metadata 13const metadata = new PhotoMetadata() 14metadata.height = 640 15metadata.width = 480 16metadata.compressed = true 17metadata.comment = "cybershoot" 18metadata.orientation = "portrait" 19metadata.photo = photo // this way we connect them 20 21// get entity repositories 22const photoRepository = AppDataSource.getRepository(Photo) 23const metadataRepository = AppDataSource.getRepository(PhotoMetadata) 24 25// first we should save a photo 26await photoRepository.save(photo) 27 28// photo is saved. Now we need to save a photo metadata 29await metadataRepository.save(metadata) 30 31// done 32console.log( 33 "Metadata is saved, and the relation between metadata and photo is created in the database too", 34)
Inverse side of the relationship
Relations can be unidirectional or bidirectional. Currently, our relation between PhotoMetadata and Photo is unidirectional. The owner of the relation is PhotoMetadata, and Photo doesn't know anything about PhotoMetadata. This makes it complicated to access PhotoMetadata from the Photo side. To fix this issue we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional. Let's modify our entities:
1import { 2 Entity, 3 Column, 4 PrimaryGeneratedColumn, 5 OneToOne, 6 JoinColumn, 7} from "typeorm" 8import { Photo } from "./Photo" 9 10@Entity() 11export class PhotoMetadata { 12 /* ... other columns */ 13 14 @OneToOne(() => Photo, (photo) => photo.metadata) 15 @JoinColumn() 16 photo: Photo 17}
1import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm" 2import { PhotoMetadata } from "./PhotoMetadata" 3 4@Entity() 5export class Photo { 6 /* ... other columns */ 7 8 @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo) 9 metadata: PhotoMetadata 10}
photo => photo.metadata
is a function that returns the name of the inverse side of the relation.
Here we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class.
Instead of passing a function that returns a property of the photo, you could alternatively simply pass a string to @OneToOne
decorator, like "metadata"
.
But we used this function-typed approach to make our refactoring easier.
Note that we should use the @JoinColumn
decorator only on one side of a relation.
Whichever side you put this decorator on will be the owning side of the relationship.
The owning side of a relationship contains a column with a foreign key in the database.
Relations in ESM projects
If you use ESM in your TypeScript project, you should use the Relation
wrapper type in relation properties to avoid circular dependency issues.
Let's modify our entities:
1import { 2 Entity, 3 Column, 4 PrimaryGeneratedColumn, 5 OneToOne, 6 JoinColumn, 7 Relation, 8} from "typeorm" 9import { Photo } from "./Photo" 10 11@Entity() 12export class PhotoMetadata { 13 /* ... other columns */ 14 15 @OneToOne(() => Photo, (photo) => photo.metadata) 16 @JoinColumn() 17 photo: Relation<Photo> 18}
1import { 2 Entity, 3 Column, 4 PrimaryGeneratedColumn, 5 OneToOne, 6 Relation, 7} from "typeorm" 8import { PhotoMetadata } from "./PhotoMetadata" 9 10@Entity() 11export class Photo { 12 /* ... other columns */ 13 14 @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo) 15 metadata: Relation<PhotoMetadata> 16}
Loading objects with their relations
Now let's load our photo and its photo metadata in a single query.
There are two ways to do it - using find*
methods or using QueryBuilder
functionality.
Let's use find*
method first.
find*
methods allow you to specify an object with the FindOneOptions
/ FindManyOptions
interface.
1import { Photo } from "./entity/Photo" 2import { PhotoMetadata } from "./entity/PhotoMetadata" 3import { AppDataSource } from "./index" 4 5const photoRepository = AppDataSource.getRepository(Photo) 6const photos = await photoRepository.find({ 7 relations: { 8 metadata: true, 9 }, 10})
Here, photos will contain an array of photos from the database, and each photo will contain its photo metadata. Learn more about Find Options in this documentation.
Using find options is good and dead simple, but if you need a more complex query, you should use QueryBuilder
instead.
QueryBuilder
allows more complex queries to be used in an elegant way:
1import { Photo } from "./entity/Photo" 2import { PhotoMetadata } from "./entity/PhotoMetadata" 3import { AppDataSource } from "./index" 4 5const photos = await AppDataSource.getRepository(Photo) 6 .createQueryBuilder("photo") 7 .innerJoinAndSelect("photo.metadata", "metadata") 8 .getMany()
QueryBuilder
allows the creation and execution of SQL queries of almost any complexity.
When you work with QueryBuilder
, think like you are creating an SQL query.
In this example, "photo" and "metadata" are aliases applied to selected photos.
You use aliases to access columns and properties of the selected data.
Using cascades to automatically save related objects
We can set up cascade options in our relations, in the cases when we want our related object to be saved whenever the other object is saved.
Let's change our photo's @OneToOne
decorator a bit:
1export class Photo { 2 // ... other columns 3 4 @OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, { 5 cascade: true, 6 }) 7 metadata: PhotoMetadata 8}
Using cascade
allows us not to separately save photos and separately save metadata objects now.
Now we can simply save a photo object, and the metadata object will be saved automatically because of cascade options.
1import { AppDataSource } from "./index" 2 3// create photo object 4const photo = new Photo() 5photo.name = "Me and Bears" 6photo.description = "I am near polar bears" 7photo.filename = "photo-with-bears.jpg" 8photo.isPublished = true 9 10// create photo metadata object 11const metadata = new PhotoMetadata() 12metadata.height = 640 13metadata.width = 480 14metadata.compressed = true 15metadata.comment = "cybershoot" 16metadata.orientation = "portrait" 17 18photo.metadata = metadata // this way we connect them 19 20// get repository 21const photoRepository = AppDataSource.getRepository(Photo) 22 23// saving a photo also save the metadata 24await photoRepository.save(photo) 25 26console.log("Photo is saved, photo metadata is saved too.")
Notice that we now set the photo's metadata
property, instead of the metadata's photo
property as before. The cascade
feature only works if you connect the photo to its metadata from the photo's side. If you set the metadata side, the metadata would not be saved automatically.
Creating a many-to-one / one-to-many relation
Let's create a many-to-one/one-to-many relation.
Let's say a photo has one author, and each author can have many photos.
First, let's create an Author
class:
1import { 2 Entity, 3 Column, 4 PrimaryGeneratedColumn, 5 OneToMany, 6 JoinColumn, 7} from "typeorm" 8import { Photo } from "./Photo" 9 10@Entity() 11export class Author { 12 @PrimaryGeneratedColumn() 13 id: number 14 15 @Column() 16 name: string 17 18 @OneToMany(() => Photo, (photo) => photo.author) // note: we will create author property in the Photo class below 19 photos: Photo[] 20}
Author
contains an inverse side of a relation.
OneToMany
is always an inverse side of the relation, and it can't exist without ManyToOne
on the other side of the relation.
Now let's add the owner side of the relation into the Photo entity:
1import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from "typeorm" 2import { PhotoMetadata } from "./PhotoMetadata" 3import { Author } from "./Author" 4 5@Entity() 6export class Photo { 7 /* ... other columns */ 8 9 @ManyToOne(() => Author, (author) => author.photos) 10 author: Author 11}
In many-to-one / one-to-many relations, the owner side is always many-to-one.
It means that the class that uses @ManyToOne
will store the id of the related object.
After you run the application, the ORM will create the author
table:
1+-------------+--------------+----------------------------+ 2| author | 3+-------------+--------------+----------------------------+ 4| id | int(11) | PRIMARY KEY AUTO_INCREMENT | 5| name | varchar(255) | | 6+-------------+--------------+----------------------------+
It will also modify the photo
table, adding a new author
column and creating a foreign key for it:
1+-------------+--------------+----------------------------+ 2| photo | 3+-------------+--------------+----------------------------+ 4| id | int(11) | PRIMARY KEY AUTO_INCREMENT | 5| name | varchar(255) | | 6| description | varchar(255) | | 7| filename | varchar(255) | | 8| isPublished | boolean | | 9| authorId | int(11) | FOREIGN KEY | 10+-------------+--------------+----------------------------+
Creating a many-to-many relation
Let's create a many-to-many relation.
Let's say a photo can be in many albums, and each album can contain many photos.
Let's create an Album
class:
1import { 2 Entity, 3 PrimaryGeneratedColumn, 4 Column, 5 ManyToMany, 6 JoinTable, 7} from "typeorm" 8 9@Entity() 10export class Album { 11 @PrimaryGeneratedColumn() 12 id: number 13 14 @Column() 15 name: string 16 17 @ManyToMany(() => Photo, (photo) => photo.albums) 18 @JoinTable() 19 photos: Photo[] 20}
@JoinTable
is required to specify that this is the owner side of the relationship.
Now let's add the inverse side of our relation to the Photo
class:
1export class Photo { 2 // ... other columns 3 4 @ManyToMany(() => Album, (album) => album.photos) 5 albums: Album[] 6}
After you run the application, the ORM will create a album_photos_photo_albums junction table:
1+-------------+--------------+----------------------------+ 2| album_photos_photo_albums | 3+-------------+--------------+----------------------------+ 4| album_id | int(11) | PRIMARY KEY FOREIGN KEY | 5| photo_id | int(11) | PRIMARY KEY FOREIGN KEY | 6+-------------+--------------+----------------------------+
Don't forget to register the Album
class with your connection in the ORM:
1const options: DataSourceOptions = { 2 // ... other options 3 entities: [Photo, PhotoMetadata, Author, Album], 4}
Now let's insert albums and photos into our database:
1import { AppDataSource } from "./index" 2 3// create a few albums 4const album1 = new Album() 5album1.name = "Bears" 6await AppDataSource.manager.save(album1) 7 8const album2 = new Album() 9album2.name = "Me" 10await AppDataSource.manager.save(album2) 11 12// create a few photos 13const photo = new Photo() 14photo.name = "Me and Bears" 15photo.description = "I am near polar bears" 16photo.filename = "photo-with-bears.jpg" 17photo.views = 1 18photo.isPublished = true 19photo.albums = [album1, album2] 20await AppDataSource.manager.save(photo) 21 22// now our photo is saved and albums are attached to it 23// now lets load them: 24const loadedPhoto = await AppDataSource.getRepository(Photo).findOne({ 25 where: { 26 id: 1, 27 }, 28 relations: { 29 albums: true, 30 }, 31})
loadedPhoto
will be equal to:
1{ 2 id: 1, 3 name: "Me and Bears", 4 description: "I am near polar bears", 5 filename: "photo-with-bears.jpg", 6 albums: [{ 7 id: 1, 8 name: "Bears" 9 }, { 10 id: 2, 11 name: "Me" 12 }] 13}
Using QueryBuilder
You can use QueryBuilder to build SQL queries of almost any complexity. For example, you can do this:
1const photos = await AppDataSource.getRepository(Photo) 2 .createQueryBuilder("photo") // first argument is an alias. Alias is what you are selecting - photos. You must specify it. 3 .innerJoinAndSelect("photo.metadata", "metadata") 4 .leftJoinAndSelect("photo.albums", "album") 5 .where("photo.isPublished = true") 6 .andWhere("(photo.name = :photoName OR photo.name = :bearName)") 7 .orderBy("photo.id", "DESC") 8 .skip(5) 9 .take(10) 10 .setParameters({ photoName: "My", bearName: "Mishka" }) 11 .getMany()
This query selects all published photos with "My" or "Mishka" names. It will select results from position 5 (pagination offset) and will select only 10 results (pagination limit). The selection result will be ordered by id in descending order. The photo albums will be left joined and their metadata will be inner joined.
You'll use the query builder in your application a lot. Learn more about QueryBuilder here.
Samples
Take a look at the samples in sample for examples of usage.
There are a few repositories that you can clone and start with:
- Example how to use TypeORM with TypeScript
- Example how to use TypeORM with JavaScript
- Example how to use TypeORM with JavaScript and Babel
- Example how to use TypeORM with TypeScript and SystemJS in Browser
- Example how to use TypeORM with TypeScript and React in Browser
- Example how to use Express and TypeORM
- Example how to use Koa and TypeORM
- Example how to use TypeORM with MongoDB
- Example how to use TypeORM in a Cordova/PhoneGap app
- Example how to use TypeORM with an Ionic app
- Example how to use TypeORM with React Native
- Example how to use TypeORM with Nativescript-Vue
- Example how to use TypeORM with Nativescript-Angular
- Example how to use TypeORM with Electron using JavaScript
- Example how to use TypeORM with Electron using TypeScript
Extensions
There are several extensions that simplify working with TypeORM and integrating it with other modules:
- TypeORM + GraphQL framework
- TypeORM integration with TypeDI
- TypeORM integration with routing-controllers
- Models generation from the existing database - typeorm-model-generator
- Fixtures loader - typeorm-fixtures-cli
- ER Diagram generator - typeorm-uml
- another ER Diagram generator - erdia
- Create, drop & seed database - typeorm-extension
- Automatically update
data-source.ts
after generating migrations/entities - typeorm-codebase-sync - Easy manipulation of
relations
objects - typeorm-relations - Automatically generate
relations
based on a GraphQL query - typeorm-relations-graphql
Contributing
Learn about contribution here and how to set up your development environment here.
This project exists thanks to all the people who contribute:
Sponsors
Open source is hard and time-consuming. If you want to invest in TypeORM's future you can become a sponsor and allow our core team to spend more time on TypeORM's improvements and new features. Become a sponsor
Gold Sponsors
Become a gold sponsor and get premium technical support from our core contributors. Become a gold sponsor
Stable Version
The latest stable version of the package.
Stable Version
0.3.20
CRITICAL
2
9.8/10
Summary
SQL injection in typeORM
Affected Versions
< 0.3.0
Patched Versions
0.3.0
9.8/10
Summary
TypeORM vulnerable to MAID and Prototype Pollution
Affected Versions
< 0.2.25
Patched Versions
0.2.25
HIGH
1
0/10
Summary
SQL Injection in typeorm
Affected Versions
< 0.1.15
Patched Versions
0.1.15
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Info: Found linked content: SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 24/30 approved changesets -- score normalized to 8
Reason
1 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: containerImage not pinned by hash: docker/oracle/Dockerfile:1: pin your Docker image by updating container-registry.oracle.com/database/express:21.3.0-xe to container-registry.oracle.com/database/express:21.3.0-xe@sha256:dcf137aab02d5644aaf9299aae736e4429f9bfdf860676ff398a1458ab8d23f2
- Info: 0 out of 1 containerImage dependencies pinned
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 25 are checked with a SAST tool
Reason
16 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-m5vv-6r4h-3vj9
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-4gmj-3p3h-gm8h
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-mqr2-w7wj-jjgr
- Warn: Project is vulnerable to: GHSA-49j4-86m8-q2jw
- Warn: Project is vulnerable to: GHSA-fpw7-j2hg-69v5
- Warn: Project is vulnerable to: GHSA-4rch-2fh8-94vw
- Warn: Project is vulnerable to: GHSA-pmh2-wpjm-fj45
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-7fh5-64p2-3v2j
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
Score
3.4
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More