Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    stingers
    @stingers
    Any help ?
    Taras Kucyj
    @Sanyco
    Hi
    @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
    @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
    @Simanto_Rahman_twitter

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

    @Entity()
    export class Product {
        @PrimaryColumn('text')
        sku: string;
    
        @Column('text')
        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
        }
    }
    
    @Entity()
    export class Category {
        @PrimaryGeneratedColumn('rowid')
        id: string;
    
        @Column("text")
        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
    @nosyminotaur
    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
    @Simanto_Rahman_twitter
    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
    @nosyminotaur
    yup, decided to do that actually. worked, thanks!
    Simanto Rahman
    @Simanto_Rahman_twitter
    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
    @DrMabuse23
    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
    ^^
    pookdeveloper
    @pookdeveloper
    Hello i have this question:
    typeorm/typeorm#5322
    Thanks!!!
    Ahmed Rebai
    @Rebaiahmed
    Hi
    Nathan
    @nspaeth
    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
    @Simanto_Rahman_twitter
    Have you tried .create()
    image.png
    Roberto Sero
    @random42
    anyone knows how to perform a merge on json fields?
    RAW4RMCS
    @RAW4RMCS
    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
    @Simanto_Rahman_twitter
    @random42 you mean in JavaScript?
    Roberto Sero
    @random42
    I meant using typeorm on postgres..
    Simanto Rahman
    @Simanto_Rahman_twitter
    Could you elaborate a bit on ‘json’ when you’re using postgres?
    rained23
    @rained23
    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?
    dima12qw
    @dima12qw
    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
    @rightisleft
    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
    @Simanto_Rahman_twitter

    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:

    Transaction:

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

    and the TransactionItem:

    @Entity('transaction_item')
    export class TransactionItem {
      @PrimaryGeneratedColumn('rowid')
      id: number;
    
      @ManyToOne(
        type => Transaction,
        transaction => transaction.items
      )
      transaction: Transaction;
    
      @ManyToOne(type => Product, { cascade: true })
      @JoinColumn()
      product: Product;
    
      @Column('int')
      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(
      TransactionItem,
      items.map(
        ({ product, qty }) =>
          ({
            product: product,
            transaction: transaction,
            qty: qty
          } as DeepPartial<TransactionItem>)
      )
    );
    
    transaction.items = transactionItems;
    database.save(transaction);

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

    {
        "stmt": "SELECT * FROM `transaction_item`;",
        "header": [
            "id",
            "qty",
            "transactionId",
            "productSku"
        ],
        "rows": [
            [
                "1",
                "1",
                "NULL",
                "063124202200"
            ],
            [
                "2",
                "1",
                "NULL",
                "06742708"
            ]
        ]
    }

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

    Jonathan Bouchard
    @Drakota

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

    export class User extends BaseEntity {
      @PrimaryGeneratedColumn()
      public id!: number;
    
      @Column()
      public firstName!: string;
    
      @ManyToMany(type => Permission)
      @JoinTable()
      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.

    syang
    @syang

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

    @Entity()
    export class Viewers {
      @PrimaryColumn()
      public q_id: string = '';
    
      @Column()
      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
    @slvrtrn

    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
      entities,
      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
    @slvrtrn
    okay, found it
    https://github.com/typeorm/typeorm/blob/1e1595e4c561995c60eef60426ef4f198d8b48cb/src/connection/ConnectionOptionsReader.ts#L106-L108
    Config command line arg is just ignored if you have defined environment variables :)
    ownsources
    @ownsources
    Hello!
    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
    @dbousamra
    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
    @dbousamra
    nvm , i solved by explicitly issuing a type to my entity annotations
    innoveltec
    @innoveltec

    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:

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

    I have the following service:

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

    And this will be my resolver:

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

    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,

    Gerry

    Antonis
    @AntonisFK
    Is this possible guys typeorm/typeorm#4537
    Jakub Duchon
    @Duchynko
    We're using Postgres and its ability to insert JSON into columns. Is there a way to map those JSON entries with a specific data model (type/class in Typescript)? E.g. if we have a table Client with a column called revenue of type JSON with fields { amount: float, currency: string }, and I'd like to map it directly to a class/type instead of just JSON.
    KanoniPan
    @KanoniP_twitter
    hello, how to unset fields from mongodb using save method? it sets values to null instead of unsetting it from db
    rogrdat
    @rogrdat
    Hello, anyone have any idea why this call below to get the nextval off a sequence grabs 12 values from the sequence instead of just one..,
    await createQueryBuilder('entity').select("nextval('test_seq')").execute();
    Sam Grönblom
    @sgronblo
    @Duchynko Yeah, you can use something like io-ts or value transformers for that
    Actually if you have a plain interface or something, you can just use @Column({type: json}) and don't need to do anything
    aRtoo
    @artoodeeto

    hello guys. Anyone tried to implement softDelete in a 1:n relationship? I keep trying but no luck seems like its not working. I have these entities:

    @Entity({ name: 'users' })
    export class User extends BaseModel {
      @DeleteDateColumn()
      deletedAt!: Date;
    
      @OneToMany(
        (type) => Post,
        (post) => post.user,
        { cascade: true }
      )
      posts!: Post[];
    }
    
    
    @Entity({ name: 'posts' })
    export class Post extends BaseModel {
    @DeleteDateColumn()
      deletedAt!: Date;
    
      @ManyToOne(
        (type) => User,
        (user) => user.posts,
        { onDelete: 'CASCADE' }
      )
      user!: User;
    }

    The onDelete: 'CASCADE' does work if softdelete is not used. but when I tried implementing softDelete it doesnt work. deletedAt column is empty and I can still retrieve the row. please some?? Ill help someone too if I can.

    3 replies
    aRtoo
    @artoodeeto

    The sql result:

    query: UPDATE `users` SET `deletedAt` = CURRENT_TIMESTAMP, `updatedAt` = CURRENT_TIMESTAMP WHERE `id` IN (?) -- PARAMETERS: [1]
    query: SELECT `User`.`id` AS `User_id`, `User`.`updatedAt` AS `User_updatedAt` FROM `users` `User` WHERE (`User`.`id` = ?) AND `User`.`deletedAt` IS NULL -- PARAMETERS: [1]
    query: COMMIT

    Post entity is not included in softdelete

    You think this is a bug?