Connection APIs

Main API

  • createConnection() - Creates a new connection and registers it in global connection manager.If connection options parameter is omitted then connection options are read from ormconfig file or environment variables.
  1. import {createConnection} from "typeorm";
  2. const connection = await createConnection({
  3. type: "mysql",
  4. host: "localhost",
  5. port: 3306,
  6. username: "test",
  7. password: "test",
  8. database: "test"
  9. });
  • createConnections() - Creates multiple connections and registers them in global connection manager.If connection options parameter is omitted then connection options are read from ormconfig file or environment variables.
  1. import {createConnections} from "typeorm";
  2. const connection = await createConnections([{
  3. name: "connection1",
  4. type: "mysql",
  5. host: "localhost",
  6. port: 3306,
  7. username: "test",
  8. password: "test",
  9. database: "test"
  10. }, {
  11. name: "connection2",
  12. type: "mysql",
  13. host: "localhost",
  14. port: 3306,
  15. username: "test",
  16. password: "test",
  17. database: "test"
  18. }]);
  • getConnectionManager() - Gets connection manager which stores all created (using createConnection() or createConnections()) connections.
  1. import {getConnectionManager} from "typeorm";
  2. const defaultConnection = getConnectionManager().get("default");
  3. const secondaryConnection = getConnectionManager().get("secondary");
  • getConnection() - Gets connection which was created by using createConnection method.
  1. import {getConnection} from "typeorm";
  2. const connection = getConnection();
  3. // if you have named connection you can specify its name:
  4. const secondaryConnection = getConnection("secondary-connection");
  • getEntityManager() - Gets EntityManager from connection.Connection name can be specified to indicate what connection’s entity manager should be taken.
  1. import {getEntityManager} from "typeorm";
  2. const manager = getEntityManager();
  3. // you can use manager methods now
  4. const secondaryManager = getEntityManager("secondary-connection");
  5. // you can use secondary connection manager methods
  • getRepository() - Gets Repository for given entity from connection.Connection name can be specified to indicate what connection’s entity manager should be taken.
  1. import {getRepository} from "typeorm";
  2. const userRepository = getRepository(User);
  3. // you can use repository methods now
  4. const blogRepository = getRepository(Blog, "secondary-connection");
  5. // you can use secondary connection repository methods
  • getTreeRepository() - Gets TreeRepository for given entity from connection.Connection name can be specified to indicate what connection’s entity manager should be taken.
  1. import {getTreeRepository} from "typeorm";
  2. const userRepository = getTreeRepository(User);
  3. // you can use repository methods now
  4. const blogRepository = getTreeRepository(Blog, "secondary-connection");
  5. // you can use secondary connection repository methods
  • getMongoRepository() - Gets MongoRepository for given entity from connection.Connection name can be specified to indicate what connection’s entity manager should be taken.
  1. import {getMongoRepository} from "typeorm";
  2. const userRepository = getMongoRepository(User);
  3. // you can use repository methods now
  4. const blogRepository = getMongoRepository(Blog, "secondary-connection");
  5. // you can use secondary connection repository methods

Connection API

  • name - Connection name. If you created nameless connection then it’s equal to “default”.You use this name when you work with multiple connections and call getConnection(connectionName: string)
  1. const connectionName: string = connection.name;
  • options - Connection options used to create this connection.Learn more about Connection Options.
  1. const connectionOptions: ConnectionOptions = connection.options;
  2. // you can cast connectionOptions to MysqlConnectionOptions
  3. // or any other xxxConnectionOptions depending on the database driver you use
  • isConnected - Indicates if a real connection to the database is established.
  1. const isConnected: boolean = connection.isConnected;
  • driver - Underlying database driver used in this connection.
  1. const driver: Driver = connection.driver;
  2. // you can cast connectionOptions to MysqlDriver
  3. // or any other xxxDriver depending on the database driver you use
  1. const manager: EntityManager = connection.manager;
  2. // you can call manager methods, for example find:
  3. const user = await manager.findOne(1);
  • mongoManager - MongoEntityManager used to work with connection entities in mongodb connections.For more information about MongoEntityManager see MongoDB documentation.
  1. const manager: MongoEntityManager = connection.mongoManager;
  2. // you can call manager or mongodb-manager specific methods, for example find:
  3. const user = await manager.findOne(1);
  • connect - Performs connection to the database.When you use createConnection it automatically calls connect and you don’t need to call it yourself.
  1. await connection.connect();
  • close - Closes connection with the database.Usually, you call this method when your application is shutting down.
  1. await connection.close();
  • synchronize - Synchronizes database schema. When synchronize: true is set in connection options it calls this method.Usually, you call this method when your application is shutting down.
  1. await connection.synchronize();
  • dropDatabase - Drops the database and all its data.Be careful with this method on production since this method will erase all your database tables and their data.Can be used only after connection to the database is established.
  1. await connection.dropDatabase();
  • runMigrations - Runs all pending migrations.
  1. await connection.runMigrations();
  • undoLastMigration - Reverts last executed migration.
  1. await connection.undoLastMigration();
  • hasMetadata - Checks if metadata for a given entity is registered.Learn more about Entity Metadata.
  1. if (connection.hasMetadata(User))
  2. const userMetadata = connection.getMetadata(User);
  • getMetadata - Gets EntityMetadata of the given entity.You can also specify a table name and if entity metadata with such table name is found it will be returned.Learn more about Entity Metadata.
  1. const userMetadata = connection.getMetadata(User);
  2. // now you can get any information about User entity
  • getRepository - Gets Repository of the given entity.You can also specify a table name and if repository for given table is found it will be returned.Learn more about Repositories.
  1. const repository = connection.getRepository(User);
  2. // now you can call repository methods, for example find:
  3. const users = await repository.findOne(1);
  • getTreeRepository - Gets TreeRepository of the given entity.You can also specify a table name and if repository for given table is found it will be returned.Learn more about Repositories.
  1. const repository = connection.getTreeRepository(Category);
  2. // now you can call tree repository methods, for example findTrees:
  3. const categories = await repository.findTrees();
  • getMongoRepository - Gets MongoRepository of the given entity.This repository is used for entities in MongoDB connection.Learn more about MongoDB support.
  1. const repository = connection.getMongoRepository(User);
  2. // now you can call mongodb-specific repository methods, for example createEntityCursor:
  3. const categoryCursor = repository.createEntityCursor();
  4. const category1 = await categoryCursor.next();
  5. const category2 = await categoryCursor.next();
  1. const userRepository = connection.getCustomRepository(UserRepository);
  2. // now you can call methods inside your custom repository - UserRepository class
  3. const crazyUsers = await userRepository.findCrazyUsers();
  • transaction - Provides a single transaction where multiple database requests will be executed in a single database transaction.Learn more about Transactions.
  1. await connection.transaction(async manager => {
  2. // NOTE: you must perform all database operations using given manager instance
  3. // its a special instance of EntityManager working with this transaction
  4. // and don't forget to await things here
  5. });
  • query - Executes a raw SQL query.
  1. const rawData = await connection.query(`SELECT * FROM USERS`);
  • createQueryBuilder - Creates a query builder, which can be used to build queries.Learn more about QueryBuilder.
  1. const users = await connection.createQueryBuilder()
  2. .select()
  3. .from(User, "user")
  4. .where("user.name = :name", { name: "John" })
  5. .getMany();
  • createQueryRunner - Creates a query runner used manage and work with a single real database connection.Learn more about QueryRunner.
  1. const queryRunner = connection.createQueryRunner();
  2. // you can use its methods only after you call connect
  3. // which performs real database connection
  4. await queryRunner.connect();
  5. // .. now you can work with query runner and call its methods
  6. // very important - don't forget to release query runner once you finished working with it
  7. await queryRunner.release();

ConnectionManager API

  • create - Creates a new connection and register it in the manager.
  1. const connection = connectionManager.create({
  2. type: "mysql",
  3. host: "localhost",
  4. port: 3306,
  5. username: "test",
  6. password: "test",
  7. database: "test"
  8. });
  • get - Gets already created connection stored in the manager by its name.
  1. const defaultConnection = connectionManager.get("default");
  2. const secondaryConnection = connectionManager.get("secondary");
  • has - Checks if a connection is registered in the given connection manager.
  1. if (connectionManager.has("default")) {
  2. // ...
  3. }