FAQ

How do I update a database schema?

One of the main responsibilities of TypeORM is to keep your database tables in sync with your entities.There are two ways that help you achieve this:

  • Use synchronize: true in your connection options:

    1. import {createConnection} from "typeorm";
    2. createConnection({
    3. synchronize: true
    4. });

    This option automatically syncs your database tables with the given entities each time you run this code. This option is perfect during development, but in production you may not want this option to be enabled.

  • Use command line tools and run schema sync manually in the command line:

    1. typeorm schema:sync

    This command will execute schema synchronization. Note, to make command line tools work, you must create an ormconfig.json file.

Schema sync is extremely fast.If you are considering the disable synchronize option during development because of performance issues,first check how fast it is.

How do I change a column name in the database?

By default, column names are generated from property names.You can simply change it by specifying a name column option:

  1. @Column({ name: "is_active" })
  2. isActive: boolean;

How can I set the default value to some function, for example NOW()?

default column option supports a function.If you are passing a function which returns a string,it will use that string as a default value without escaping it.For example:

  1. @Column({ default: () => "NOW()" })
  2. date: Date;

How to do validation?

Validation is not part of TypeORM because validation is a separate processnot really related to what TypeORM does.If you want to use validation use class-validator - it works perfectly with TypeORM.

What does “owner side” in a relations mean or why we need to use @JoinColumn and @JoinTable?

Let’s start with one-to-one relation.Let’s say we have two entities: User and Photo:

  1. @Entity()
  2. export class User {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column()
  6. name: string;
  7. @OneToOne()
  8. photo: Photo;
  9. }
  1. @Entity()
  2. export class Photo {
  3. @PrimaryGeneratedColumn()
  4. id: number;
  5. @Column()
  6. url: string;
  7. @OneToOne()
  8. user: User;
  9. }

This example does not have a @JoinColumn which is incorrect.Why? Because to make a real relation, we need to create a column in the database.We need to create a column userId in photo or photoId in user.But which column should be created - userId or photoId?TypeORM cannot decide for you.To make a decision, you must use @JoinColumn on one of the sides.If you put @JoinColumn in Photo then a column called userId will be created in the photo table.If you put @JoinColumn in User then a column called photoId will be created in the user table.The side with @JoinColumn will be called the “owner side of the relationship”.The other side of the relation, without @JoinColumn, is called the “inverse (non-owner) side of relationship”.

It is the same in a @ManyToMany relation. You use @JoinTable to show the owner side of the relation.

In @ManyToOne or @OneToMany relations, @JoinColumn is not necessary becauseboth decorators are different, and the table where you put the @ManyToOne decorator will have the relational column.

@JoinColumn and @JoinTable decorators can also be used to specify additionaljoin column / junction table settings, like join column name or junction table name.

How do I add extra columns into many-to-many (junction) table?

It’s not possible to add extra columns into a table created by a many-to-many relation.You’ll need to create a separate entity and bind it using two many-to-one relations with the target entities(the effect will be same as creating a many-to-many table),and add extra columns in there. You can read more about this in Many-to-Many relations.

How to use TypeORM with a dependency injection tool?

In TypeORM you can use service containers. Service containers allow you to inject custom services in some places, like in subscribers or custom naming strategies. For example, you can get access to ConnectionManager from any place using a service container.

Here is an example for how you can set up typedi service containers with TypeORM. Note: you can setup any service container with TypeORM.

  1. import {useContainer, createConnection} from "typeorm";
  2. import {Container} from "typedi";
  3. // its important to setup container before you start to work with TypeORM
  4. useContainer(Container);
  5. createConnection({/* ... */});

How to handle outDir TypeScript compiler option?

When you are using the outDir compiler option, don’t forget to copy assets and resources your app is using into the output directory.Otherwise, make sure to setup correct paths to those assets.

One important thing to know is that when you remove or move entities, the old entities are left untouched inside the output directory.For example, you create a Post entity and rename it to Blog,you no longer have Post.ts in your project. However, Post.js is left inside the output directory.Now, when TypeORM reads entities from your output directory, it sees two entities - Post and Blog.This may be a source of bugs.That’s why when you remove and move entities with outDir enabled, it’s strongly recommended to remove your output directory and recompile the project again.

How to use TypeORM with ts-node?

You can prevent compiling files each time using ts-node.If you are using ts-node, you can specify ts entities inside your connection options:

  1. {
  2. entities: ["src/entity/*.ts"],
  3. subscribers: ["src/subscriber/*.ts"]
  4. }

Also, if you are compiling js files into the same folder where your typescript files are,make sure to use the outDir compiler option to preventthis issue.

Also, if you want to use the ts-node CLI, you can execute TypeORM the following way:

  1. ts-node ./node_modules/bin/typeorm schema:sync

How to use Webpack for the backend?

Webpack produces warnings due to what it views as missing require statements — require statements for all drivers supported by TypeORM. To suppress these warnings for unused drivers, you will need to edit your webpack config file.

  1. const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
  2. module.exports = {
  3. ...
  4. plugins: [
  5. //ignore the drivers you don't want. This is the complete list of all drivers -- remove the suppressions for drivers you want to use.
  6. new FilterWarningsPlugin({
  7. exclude: [/mongodb/, /mssql/, /mysql/, /mysql2/, /oracledb/, /pg/, /pg-native/, /pg-query-stream/, /redis/, /sqlite3/]
  8. })
  9. ]
  10. };

Bundling Migration Files

By default Webpack tries to bundle everything into one file. This can be problematic when your project has migration files which are meant to be executed after bundled code is deployed to production. To make sure all your migrations can be recognized and executed by TypeORM, you may need to use “Object Syntax” for the entry configuration for the migration files only.

  1. const glob = require('glob');
  2. const path = require('path');
  3. module.exports = {
  4. // ... your webpack configurations here...
  5. // Dynamically generate a `{ [name]: sourceFileName }` map for the `entry` option
  6. // change `src/db/migrations` to the relative path to your migration folder
  7. entry: glob.sync(path.resolve('src/db/migrations/*.ts')).reduce((entries, filename) => {
  8. const migrationName = path.basename(filename, '.ts');
  9. return Object.assign({}, entries, {
  10. [migrationName]: filename,
  11. });
  12. }, {}),
  13. resolve: {
  14. // assuming all your migration files are written in TypeScript
  15. extensions: ['.ts']
  16. },
  17. output: {
  18. // change `path` to where you want to put transpiled migration files.
  19. path: __dirname + '/dist/db/migrations',
  20. // this is important - we want UMD (Universal Module Definition) for migration files.
  21. libraryTarget: 'umd',
  22. filename: '[name].js',
  23. },
  24. };

Also, since Webpack 4, when using mode: 'production', files are optimized by default which includes mangling your code in order to minimize file sizes. This breaks the migrations because TypeORM relies on their names to determine which has already been executed. You may disable minimization completely by adding:

  1. module.exports = {
  2. // ... other Webpack configurations here
  3. optimization: {
  4. minimize: false,
  5. },
  6. };

Alternatively, if you are using the UglifyJsPlugin, you can tell it to not change class or function names like so:

  1. const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
  2. module.exports = {
  3. // ... other Webpack configurations here
  4. optimization: {
  5. minimizer: [
  6. new UglifyJsPlugin({
  7. uglifyOptions: {
  8. keep_classnames: true,
  9. keep_fnames: true
  10. }
  11. })
  12. ],
  13. },
  14. };

Lastly, make sure in your ormconfig file, the transpiled migration files are included:

  1. // TypeORM Configurations
  2. module.exports = {
  3. // ...
  4. migrations: [
  5. // this is the relative path to the transpiled migration files in production
  6. 'db/migrations/**/*.js',
  7. // your source migration files, used in development mode
  8. 'src/db/migrations/**/*.ts',
  9. ],
  10. };