Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    hi, guys, is there a built-in mechanism to populate entity from Json like new User().fromJson(data)
    Juliano Lazzarotto
    Is it possible to use @Query( type ---> using a ViewEntity????)
    I keep receiving an error GraphQL cannot determine the output type - Dunno if the ViewEntity works as Entity
    NVM --- I forgot the annotations :D my bad
    Juliano Lazzarotto
    findAndCount and Count are supposed to work with MySQL? I'm receiving an error -> SELECT COUNT(DISTINCT()) FROM ....
    was this a dumb question or there are no active users to answer it? "hi, guys, is there a built-in mechanism to populate entity from Json like new User().fromJson(data)"
    Iv Po
    Hi, any one knows why @BeforeUpdate() decorator/subscriber event dont work with mongodb? I cannot find code related to this in MongoQueryRunner, seems like its just calls methods from mongo driver without using Broadcaster or something like UpdateQueryBuilder does. I am trying to use repository methods replaceOne(), update(), when i use save() for new Entity @BeforeInsert() event is triggered, but update events are not. I know that mongodb is experimental, but is it okay or i am doing something wrong?)
    @dan-conachi as far as I know there no such method
    I'am inserting multiple related entities to a postgres db. In the logs I see multiple transaction being started even though I don't start a transaction myself.
    I assume that typeorm automatically starts transaction in certain cases so it can rollback however is this somewhere documented on what behvaiour I can expect?
    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.