Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    Jimin Park
    I can't find descriptions about findOneOrFail() in the official API doc.

    @jimin4 - from their type defsin Repository.d.ts

     * Finds first entity that matches given options.
    findOneOrFail(id?: string | number | Date | ObjectID, options?: FindOneOptions<Entity>): Promise<Entity>;
     * Finds first entity that matches given options.
    findOneOrFail(options?: FindOneOptions<Entity>): Promise<Entity>;
     * Finds first entity that matches given conditions.
    findOneOrFail(conditions?: FindConditions<Entity>, options?: FindOneOptions<Entity>): Promise<Entity>;
     * Executes a raw SQL query and returns a raw database results.
     * Raw query execution is supported only by relational databases (MongoDB is not supported).`

    Works exactly the same as FindOne in terms of function signature so all docs from there are applicable

    For @AfterLoad decorator in Entity Listener, is it possible to update the object and have it persist to DB? I'm having some trouble with that. Not doing anything special just updating a property. Do I need to call some save or update function.
    Currently with this approach: this.property = value
    Got my answer - need to create a transaction to save the object!

    Hi all, in typeorm entity manager API documentation, there is method named release, it is used to release query runner of an entity manager. It also says here it should only be used when query runner was created and managed manually.

    My question, what does "Used only when query runner was created and managed manually" means, and what is the use case for release to be used

    Sorry for bad english, english not my first language

    Marija Talevska
    Hi all, is there a way to serverless deploy typeorm with express apis to AWS?
    Dustin Lacewell
    Is there anyway to get a groupby where you get an object mapping group key to an array of model instances in each group?
    does anyone know how i can compile and point to the ormconfig.json in the dist/ dir rather than the one at the root of my project?
    this is when running via node, not CLI
    Hi All,
    can we get user request inside entity suscribers
    Mark V

    Hey there everyone, we recently ran a psql CREATE INDEX CONCURRENTLY migration through the TypeORM migration system using queryRunner.connection.query, and instead of async/await-ing the response, we defined .then, .error, and .finally callbacks which would log when it was finished, so our webapp wouldn't be blocked while the concurrent index creation finished up.

    On one of our servers, we see the log for "starting" the migration, but we never saw our logs for the .then, .error, and .finally callbacks. This server was our instance with the most number of rows, and index creation definitely took longer than a couple minutes. But we verified in the DLL that the migration had successfully completed, despite never seeing our log statements.

    Looking in the PSQL logs, I see that T+4s after the migration started, this error was printed LOG: could not receive data from client: Connection reset by peer.

    Does TypeORM or node have some sort of thing that kills promises after 4s? And if so, why didn't the query get killed or error out? My intuition says that normally the query would get canceled if a promise timeout occured

    Karl Clement
    Hi all, in Entity objects I have multiple @Generated columns and I keep getting errors null value in column "id" of relation "user" violates not-null constraint. Does the generation actually work or I need to set defaults in migrations? What does the @Decorator do?
    Key Kim

    Hello there, I'm trying to convert raw mysql code to typeorm

    how can i convert under sql?

    select * from (
        select acv.id, acv.week_title, MAX(acs.id) as m from development.audition_chart_v2 acv
        inner join development.audition_chart_snapshots acs
            ON acv.id = acs.audition_chart_id and acv.status = 'DONE'
        group by acv.id
    ) as a
    left join development.audition_chart_snapshots acs2 on acs2.id = a.m
    Hi All can we create multiple column in join table?
    Karl Clement
    Hi all, in Entity objects I have multiple @Generated columns and I keep getting errors null value in column "id" of relation "user" violates not-null constraint. Does the generation actually work or I need to set defaults in migrations? What does the @Decorator do?
    I'm looking for a way to order by a property calculated with @AfterLoad decorator... Anyone can help?
    Maarten van Veen

    Hi all,
    I have a NestJS backend with TypeORM connected to a Postgres db.
    The db has a table building_daly_max with a column named visitdate of type date. Data like the following:

    building_id capacity wifi reserved workplaces visitdate
    119    395        0        2020-10-26
    13    354        0        2020-11-01
    111    31        0        2020-11-01
    120    530        0        2020-11-01

    The entity looks like this:

    @Entity({ name: 'building_daily_max' })
    export class BuildingDailyOccupancyEntity {
      @ManyToOne(() => BuildingEntity)
      @JoinColumn({ name: 'building_id' })
      building: BuildingEntity;
      @PrimaryColumn({ name: 'visitdate', type: 'date' })
      date: Date;
      @Column({ name: 'capacity' })
      capacity: number;
      @Column({ name: 'wifi' })
      maxWifiClientCount: number;
      @Column({ name: 'reserved' })
      maxReservationCount: number;
      @Column({ name: 'workplaces' })
      maxWorkplaceCount: number;

    Querying by date only returns the first of the matching rows. However if I run the query typeorm performed manually in dbeaver I get all matching rows.
    Also when running the raw query with the entitymanager returns all the rows.
    Is this a bug in typeorm or am I missing something?

    // Returns first row only
        const result = await this.dailyOccupancyRepository.find({
            relations: ['building'],
            where: {
              date: '2020-11-16',
    // Returns first row only
        const result = await this.dailyOccupancyRepository.createQueryBuilder()
          .where('visitdate = :visitdate', { visitdate: '2020-11-16'})
    // Returns all rows, but mapping to entities is a pain
        const result = await this.entityManager.query('select * from building_daily_max bdm inner join buildings b on bdm.building_id = b.building_id where bdm.visitdate = $1', ['2020-11-16']);
    2 replies
    Kevin Elliott
    Hello, I need to set statement_timeout for a repository, any ideas?
    Alex McKay
    Hi Gang, I am only using Javascript and cannot for the life of me work out how to use the UpdateDate column without using the Typescript decorator. I've had a look through the source code as well as the documentation but cannot find my answer. Does anyone know?
    Alex McKay
    time works!

    I have a problem with where clause and boolean value in TypeORM, like below:

    async getUserProjects(user: User, isFavorite: boolean): Promise<User[]> {
            const data = await this.conn.getRepository(User).find({
                where: {
                    userId: user,
                    favorite: isFavorite
        type: 'bool'
      favorite: boolean;

    why this find not work properly and always return me value where favorite is false?
    when my fav == true return me all data when favorite == false..., can someone tell me what is wrong here?

    Sanjar B
    hi! can I use typeorm with javascript (not typescript) and using ESM imports (import {} from '') without babel? I using nodejs 15 and Mozilla documentation said that decorators (@somedecorator) supports natively by last versions
    but I get an error
    SyntaxError: Invalid or unexpected token
    @Column({ nullable: true, default: null }) baseCurrency: string;
    Hi for the above column in my entity migration are getting generated each and every time for this field , Any suggestion please

    Hi there, using typeOrm on node application I have this error when i start transaction to mysql:

    (node:21) UnhandledPromiseRejectionWarning: QueryFailedError: ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction
        at new QueryFailedError (/opt/app/node_modules/typeorm/error/QueryFailedError.js:11:28)
        at Query.<anonymous> (/opt/app/node_modules/typeorm/driver/mysql/MysqlQueryRunner.js:170:45)
        at Query.<anonymous> (/opt/app/node_modules/mysql/lib/Connection.js:526:10)
        at Query._callback (/opt/app/node_modules/mysql/lib/Connection.js:488:16)
        at Query.Sequence.end (/opt/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
        at Query.ErrorPacket (/opt/app/node_modules/mysql/lib/protocol/sequences/Query.js:92:8)
        at Protocol._parsePacket (/opt/app/node_modules/mysql/lib/protocol/Protocol.js:291:23)
        at Parser._parsePacket (/opt/app/node_modules/mysql/lib/protocol/Parser.js:433:10)
        at Parser.write (/opt/app/node_modules/mysql/lib/protocol/Parser.js:43:10)
        at Protocol.write (/opt/app/node_modules/mysql/lib/protocol/Protocol.js:38:16)
        at Socket.<anonymous> (/opt/app/node_modules/mysql/lib/Connection.js:88:28)
        at Socket.<anonymous> (/opt/app/node_modules/mysql/lib/Connection.js:526:10)
        at Socket.emit (events.js:315:20)
        at addChunk (internal/streams/readable.js:309:12)
        at readableAddChunk (internal/streams/readable.js:284:9)
        at Socket.Readable.push (internal/streams/readable.js:223:10)
    (node:21) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 377404)
    21 - 2021-03-09T18:30:52.823Z - [ExceptionInterceptor] Database Exception - ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction  
    Error: Database Exception
        at PartiesService.deleteContractParties (/opt/app/dist/apps/contracts-api/main.js:10592:19)
        at runMicrotasks (<anonymous>)
        at processTicksAndRejections (internal/process/task_queues.js:93:5)
        at async ContractsService.update (/opt/app/dist/apps/contracts-api/main.js:11193:9)
    21 - 2021-03-09T18:30:52.824Z - [ExceptionInterceptor] Catched DatabaseException exception -> throw InternalServerErrorException 
    21 - 2021-03-09T18:30:52.826Z - [ExceptionHandler] DatabaseException: {"type":"DatabaseException","subType":"Party","internalMessage":"ER_LOCK_WAIT_TIMEOUT: Lock wait timeout exceeded; try restarting transaction"}  
    Error: Database Exception
        at CatchSubscriber.selector (/opt/app/dist/apps/contracts-api/main.js:1332:42)
        at CatchSubscriber.error (/opt/app/node_modules/rxjs/internal/operators/catchError.js:48:31)
        at MergeMapSubscriber.OuterSubscriber.notifyError (/opt/app/node_modules/rxjs/internal/OuterSubscriber.js:26:26)
        at InnerSubscriber._error (/opt/app/node_modules/rxjs/internal/InnerSubscriber.js:31:21)
        at InnerSubscriber.Subscriber.error (/opt/app/node_modules/rxjs/internal/Subscriber.js:72:18)
        at SwitchMapSubscriber.Subscriber._error (/opt/app/node_modules/rxjs/internal/Subscriber.js:92:26)
        at SwitchMapSubscriber.Subscriber.error (/opt/app/node_modules/rxjs/internal/Subscriber.js:72:18)
        at /opt/app/node_modules/rxjs/internal/util/subscribeToPromise.js:10:43
        at runMicrotasks (<anonymous>)
        at processTicksAndRejections (internal/process/task_queues.js:93:5)

    some one can help me to fix it? any hint or ideas are appreciated

    Not sure if this is on the right track but, from the error message it seems, that the DB transaction is taking a longer time that the configured timeout on the db lock - maybe try and simpler/faster query or adjust the timeout values
    Arun SD
    Hi guys anybody have any idea on how to mark a migration already ran in typeorm?
    Deepak Bansal
    what the datatype for tsvector col?
    Lawrence Bethlenfalvy
    How much ram is TypeORM supposed to consume? I'm getting an OOM at 2GB with no data during startup, but I don't have a profiler and I really didn't expect to need one this early.
    hey guys, i have this error QueryFailedError: insert or update on table "role_users_user" violates foreign key constraint "FK_ed6edac7184b013d4bd58d60e54" and i can't wrap my head around it. all i'm doing is inserting an email to the database
    2 replies
    Hello everybody, maybe Somebody has this warning in typeorm? How it fix?
    Deprecated as of 10.7.0. highlight(lang, code, ...args) has been deprecated. Deprecated as of 10.7.0. Please use highlight(code, options) instead.highlightjs/highlight.js#2277
    Andre Reinoso Aranda
    MongoDB Typeorm: as $ lookup works with typeorm, it doesn't return data like it would from console
    Justin Levi Winter

    Hi all, I'm new to typeorm but I'm seeing a very strange issue with the synchronize: true functionality when I modify an entity with a ManytoMany relationship. In short, any data that is in the join table before making the entity change, is gone after.

    Here is my Project Entity

    export class Project extends BaseEntity {
      @Field(() => Int)
      id: number;
      name: string;
      @Field({ nullable: true })
      @Column("text", { nullable: true })
      cluster?: string;
      @ManyToMany((type) => Group, (group) => group.projects, { lazy: true })
      @Field((type) => [Group], { nullable: true })
      groups?: Group[];

    Here is my Group Entity

    export class Group extends BaseEntity {
      @Field(() => String)
      id: string;
      name: string;
      @Field({ nullable: true })
      type: string;
      @Field({ nullable: true })
      @Column("text", { nullable: true })
      currency: string;
      @Field((type) => [Project])
      @ManyToMany((type) => Project, (project) => project.groups, { lazy: true })
      projects: Project[];
      @ManyToMany((type) => Modifier, (modifier) => modifier.group, { lazy: true })
      @Field((type) => [Modifier])
      modifiers: Modifier[];

    If I add a new field to either the Group or the Project, the migration is automatically run and the following queries

    query: CREATE TABLE "temporary_project" ("id" integer PRIMARY KEY NOT NULL, "name" text NOT NULL, "cluster" text, "asdfa" text)
    query: INSERT INTO "temporary_project"("id", "name", "cluster") SELECT "id", "name", "cluster" FROM "project"
    query: DROP TABLE "project"
    query: ALTER TABLE "temporary_project" RENAME TO "project"
    The project_groups_group table has data before, and is empty after the migration is finished
    Wondering why the migration would impact the join table as I'm not seeing any query that would even update that?
    Justin Levi Winter
    I posted a working example here:

    How to get count and num of relation.

    but it's not work

    Noda Hikaru
    Hi Everyone.
    Is there any way to select only few related table columns with find() method?
    Hi Everyone.
    I have a question on Stackoverflow, please have a look and help me. Thank you
    Hi guys, Who knows how to make the order of fields in database consistent with the order of attribute declaration in entity?
    I have a question ,plz have a look and help,thank you
    Hi coders, is there anyway to make a column type have a default transformer other than creating a custom one and adding it to all columns needed
    John Munson

    Does anyone know if it's possible to set a field to null using the save method? Is there some fancy trick that I'm unaware of? Do I need to use some sort of helper function like IsNull when you're working with the find methods?

    For example...

    // Let's find Jeff and get rid of his stupid middle name
    const jeff = await userRepository.findOne({firstName: 'Jeff'})
    jeff.middleName = null
    await userRepository.save(jeff)
    // Doesn't work... Jeff still has a middle name
    I know I could use the update method to accomplish this, but my use case is dependent on the TypeORM events/subscribers system, and update unfortunately does not work with the event system
    Tristan Blackwell

    Using TypeOrm for the first time against an already existing schema, the table names are plural and PascalCase and the entities should be singular. Therefore I'm using

    export class AccessLog {

    To define the entity. When I run migrate:generate it generates a change script that tries to create that Table AccessLogs even though it already exists.

    If I change the table name to lowercase:

    export class AccessLog {

    the problem goes away - but then the mapping in the Entity decorator is wrong and a newly created database with these migrations with generate the lowercase table name, which won't match all the other existing instances of the database. Surely I can't be the first person who doesn't have lowercase or snake_case table names?