Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    thank @warreee I found and use now on the entity static toClass(data: Object) { return plainToClass(Class, data, { excludeExtraneousValues: true }) }
    Shaishav Pidadi
    Hey, How can I add and remove specific elements from the array field in typeORM Postgres?
    Cihan Bebek

    Hi! I'm facing an issue with typeorm that I'm having trouble solving:

    I have a entity

    class MyEntity implements MyEntityInterface {
      @PrimaryColumn({ type: 'int' })
      public id: number;
      @Column({ type: 'varchar' })
      public message: string;

    now when I do a queryBuilder and a getMany(), I would like to have this new field in the result which is aggregated from other database tables


           // query builder for myEntity
            .addSelect(`EXISTS (
              SELECT true
              FROM other_table`, 'myAggregateField'

    how can I include the myAggregateField in the result?

    atm typeorm does some magic and cant build the MyEntity-object with the myAggregateField value in it
    I tried simply adding public myAggregateField?: boolean; to the MyEntity-class, but it didnt help
    Vinícius do Carmo
    Hi you all! What is the safer method to get the old values of my entity in my afterUpdate inside my Surbscriber class? thanks
    Bhuvin Thakker
    Hi guys,
    I am using Typeorm with Postgres.
    My Problem is:
    I have a column with timestamp type, which has a default value as now.
    I intend to use this column as a cursor for Paging i.e. GreaterThan the maximum date of the Last page.
    But here there is a problem that there is happening a difference of milliseconds happening when I read.
    For e.g.:
    In DB: 2019-12-18 16:10:20.659202+01
    When read through TypeOrm: 2019-12-18T16:10:20.659Z
    Can you please help me?
    I'm farcing this issue :UnhandledPromiseRejectionWarning: QueryFailedError: ER_LOCK_DEADLOCK: Deadlock found when trying to get lock; try restarting transaction
    Any help ?
    Taras Kucyj
    @Index({ fulltext: true }) @Column({type: 'tsvector'}) descriptionTsVector: string;
    Where i can read more about use fulltext and tsvector?
    1 reply
    inset update and select data
    Lev Kuznetsov

    I'm getting an error in a browser app bundled using web pack with sql.js@1.1.0:

    TypeError: Cannot read property 'Database' of undefined
          at SqljsDriver.eval (webpack:///./node_modules/typeorm/browser/driver/sqljs/SqljsDriver.js?:278:62)
          at step (webpack:///./node_modules/tslib/tslib.es6.js?:120:23)
          at Object.eval [as next] (webpack:///./node_modules/tslib/tslib.es6.js?:101:53)
          at eval (webpack:///./node_modules/tslib/tslib.es6.js?:94:71)
          at new Promise (<anonymous>)
          at Module.__awaiter (webpack:///./node_modules/tslib/tslib.es6.js?:90:12)
          at SqljsDriver.createDatabaseConnectionWithImport (webpack:///./node_modules/typeorm/browser/driver/sqljs/SqljsDriver.js?:272:63)
          at SqljsDriver.eval (webpack:///./node_modules/typeorm/browser/driver/sqljs/SqljsDriver.js?:137:56)
          at step (webpack:///./node_modules/tslib/tslib.es6.js?:120:23)
          at Object.eval [as next] (webpack:///./node_modules/tslib/tslib.es6.js?:101:53)

    it looks like it's inside SqljsDriver.prototype.createDatabaseConnectionWithImport = function (database) at line isLegacyVersion = typeof this.sqlite.Database === "function";, downgrading to sql.js@0.5.0 solves that

    Simanto Rahman

    Hey guys, I'm having a bit of problem with ManyToMany relationship
    My entities are:

    export class Product {
        sku: string;
        name: string;
        @Column({ name: 'cost_price', type: 'real' })
        costPrice: number;
        @Column({ name: 'sell_price', type: 'real' })
        sellPrice: number;
        @Column('datetime', { name: 'creation_date' })
        creationDate: Date;
        @Column('datetime', { name: 'mod_date' })
        modificationDate: Date
        @ManyToMany(type => Category)
        @JoinTable({name: 'product-categories'})
        categories: Category[];
        static create = (props: Product) => {
            let product = new Product()
            product.sku = props.sku
            product.name = props.name
            product.costPrice = props.costPrice
            product.sellPrice = props.sellPrice
            product.creationDate = props.modificationDate
            product.modificationDate = props.modificationDate
            product.categories = props.categories
            return product
    export class Category {
        id: string;
        name: string;
        @Column('datetime', { name: 'creation_date' })
        creationDate: Date;
        static create = (props: { name: string, creationDate: Date }) => {
            let category = new Category()
            category.name = props.name
            category.creationDate = props.creationDate
            return category

    I'm creating new rows using this bit of code:

    let beverageCategory = Category.create({
      creationDate: new Date(),
      name: 'Beverage'
    await categoryDb.save(beverageCategory)
    let pepsi = Product.create({
      sku: '10000001',
      categories: [beverageCategory],
      costPrice: 2.49,
      sellPrice: 2.94,
      creationDate: new Date(),
      modificationDate: new Date(),
      name: 'Pepsi 2L'
    await productDb.save(pepsi)

    But nothing shows up in the product-categories table

    Harsh Pathak
    If I set synchronize to false, can I use the database with only the fields I need in TypeORM? I have a table with a lot of fields with a lot of relationships between them, and I just need to update two fields only that are plain columns, no relations with any other tables. Is it safe to just create a class with those fields and set synchronize=false in it?
    Simanto Rahman
    I can only say, give it a try on that. Would be a fun and short experiment. I do believe it ought to work.
    Harsh Pathak
    yup, decided to do that actually. worked, thanks!
    Simanto Rahman
    PS: I did fix the problem. The problem was the product entity owning ManyToMany relation with Category, needed the category objects to have a valid id. And since I was creating the Category objects to add to Product didn't have reference to db generated keys, it couldn't recognize it. If I draw the same object from database before passing onto Products, it works like magic.
    Pascal Brewing
    Hey maybe you are interested in your ranking https://brainhub.eu/blog/node-js-open-source-projects-2019/ 👍👍👍
    Thx dir thus great tool
    For this
    Hello i have this question:
    Ahmed Rebai
    Is there an analog to .insert(...) that returns the created object (e.g., inserted data + generated keys), or should I just merge them afterward, or make a new query to get the inserted data?
    Simanto Rahman
    Have you tried .create()
    Roberto Sero
    anyone knows how to perform a merge on json fields?
    Good evening! Does somebody know how to update nested fields with oneToMany and manyToOne. I get GraphQL error: No entity column "items" was found. :(
    Simanto Rahman
    @random42 you mean in JavaScript?
    Roberto Sero
    I meant using typeorm on postgres..
    Simanto Rahman
    Could you elaborate a bit on ‘json’ when you’re using postgres?
    Hi, I am curious, I read the typeorm OneToOne documentation of User and Profile, it show that the User table holds the foreign key of Profile? Is this the right way or it just an example, but reading the @JoinColumn description it said about the owner side which User is make sense as the owner of the Profile. Most of the time I put the FK in the Profile. Is this a convention or just a matter of style?
    Hi all! I'm currently working on a project with nestjs and typeorm. I use nestjsx-crud. I'm facing with a problem with a custom many-to-many relationship like in this example : https://github.com/typeorm/typeorm/issues/1224#issuecomment-506631201. So , for example I want to insert a user with groups :
    {name: "blabla",
     groups: [{name: "blabla}, {name: "test"}]
    and it throws error: "group_id" violates not null constraint
    How to setup cascades for this type of relations?
    Jack Murphy
    Hello - i'm looking for some clarity on a project called class_transformer. I believe it was originally created by the same author as typeorm.
    I think @pleerock started the project?
    Simanto Rahman

    Hey folks,
    I've been having trouble with One-To-Many Many-To-One Relation. I have a Transaction entity which houses an array of TransactionItem and the entire thing use O2M M2O model. But the child entity never updates the foreign key for the parent (with O2M) row. Here is the prototype for it:


    export class Transaction {
      id: number;
      @Column({ type: 'real', precision: 3, nullable: false })
      price: number;
      @Column({ type: 'real', precision: 3, nullable: false })
      paid: number;
      timestamp: Date;
        type => TransactionItem,
        item => item.transaction,
        { eager: true, cascade: true }
      items: TransactionItem[];
      @Column({ enum: PaymentMethod })
      paymentMethod: PaymentMethod;

    and the TransactionItem:

    export class TransactionItem {
      id: number;
        type => Transaction,
        transaction => transaction.items
      transaction: Transaction;
      @ManyToOne(type => Product, { cascade: true })
      product: Product;
      qty: number;

    This is the process of adding to the database:

    // create transaction first
    let transaction = database.create(Transaction, {
      price: total,
      paid: value,
      timestamp: new Date(),
      paymentMethod: PaymentMethod.credit
    // create transaction items
    let transactionItems = database.create(
        ({ product, qty }) =>
            product: product,
            transaction: transaction,
            qty: qty
          } as DeepPartial<TransactionItem>)
    transaction.items = transactionItems;

    this is the output I get from the TransactionItem table after adding the data:

        "stmt": "SELECT * FROM `transaction_item`;",
        "header": [
        "rows": [

    Any help to identify the problem and a potential solution is greatly appreciated.

    Jonathan Bouchard

    Do you guys know how to create a listener for beforeUpdate of a many-to-many relationship in an entity?

    export class User extends BaseEntity {
      public id!: number;
      public firstName!: string;
      @ManyToMany(type => Permission)
      public permissions!: Permission[]; 

    Doing user.firstName = "test" triggers the beforeUpdate subscriber, but user.permissions.push(something) (in this case it will be an insert but you get the point) doesn't and I need to run an action there without having to change every single line to add what I want.


    How can I set up my eslint rule so that typeorm don't cause false positive error message?

    export class Viewers {
      public q_id: string = '';
      public owner_id: string = '';

    the above code cause my eslint complain as following

    8:3 error Type string trivially inferred from a string literal, remove type annotation

    Serge Klochkov

    I have a typescript project which uses TypeORM and I am trying to make migrations generator work appropriately. Currently, I am struggling with snake case strategy which we use to transform Entities column names (i.e. orderNum -> order_num).

    In my package json, I defined "typeorm": "ts-node --transpile-only ./node_modules/typeorm/cli.js -f ormconfig.ts". I tried --config as well, no luck.

    ormconfig.ts is like:

    export = {
      type: 'postgres',
      ..., // snip 20 more lines
      namingStrategy: new SnakeCaseStrategy(),
    } as PostgresConnectionOptions

    When I try to run it in the console like yarn typeorm migration:generate -n Foo, it seems like configuration file is completely ignored (environment variables are picked instead). As a result I get a migration full of alters like order_num -> orderNum (which is wrong). If I put something like console.log in the ormconfig.ts file, I obviously see no print as well (cause for some reason it is ignored).

    So I am looking for an advice on how to finally make this work...

    Serge Klochkov
    okay, found it
    Config command line arg is just ignored if you have defined environment variables :)
    I have an abstract question
    What if I have to build some big query with many conditions but not every field is required like
    'user.field = :x' and I don't get x from a user of api. I can see only two ways now but I don't like it
    The first is something like x ? 'user.field = :x' : '1=1'
    The second is using 'if' condition for every .andWhere block
    Maybe exist a solution for this case?
    Dominic Bou-Samra
    Is typeorm incompatible with transpileOnly mode for TS?

    I receive this:

    DataTypeNotSupportedError: Data type "Object" in "Study.status" is not supported by "postgres" database. when I enable it.

    Dominic Bou-Samra
    nvm , i solved by explicitly issuing a type to my entity annotations

    I am creating a graphql api using nestjs, type-graphql and typeorm. I am having trouble finding out how to do a certain query. Let's say i have the following entities:

    @ObjectType({ description: 'The user model' })
    export class User extends BaseEntity {
      @Field(type => ID)
      readonly id: string;
      email: string;
      password: string;
      @Field(type => [Project], { nullable: true })
      @ManyToMany(type => Project)
      projects?: Project[];
    @ObjectType({ description: 'The project model' })
    export class Project extends BaseEntity {
      @Field(type => ID)
      readonly id: string;
      description: string;
      @Field(type => [User], { nullable: true })
      @ManyToMany(type => User)
      participants?: User[];

    I have the following service:

    import { includes } from 'lodash';
    export class ProjectService {
        private projectRepository: Repository<Project>,
        private userRepository: Repository<User>,
      ) {}
      async loadAllForUser(
        userId: string
      ): Promise<Project[]> {
        const projects = await this.projectRepository.find(
              relations: ['participants'],
        return projects.filter(project =>
            project.participants.map(participant => participant.id),

    And this will be my resolver:

    @Resolver( of => Project)
    export class ProjectResolver {
        private projectService: ProjectService,
        private userService: UserService,
      ) {}
      @Query(returns => [Project])
      async myProjects(
        @GqlUser() user: User,
      ) {
        return await this.projectService.loadAllForUser(

    As you can see in my project service i am just fetching all the projects with the find method and then afterwards i am filtering this list using includes from lodash to filter out only the projects that contains the userid. Isn't there a way to add some sort of operation inside the find method of the project repository like a 'where' or 'in' so that i can filter it directly from there instead of manually filtering and using the includes from lodash? I even have no idea if this is even correct the way i am manually filtering?

    Kind regards,