Search code examples
javascriptpostgresqltypeorm

TypeORM - appending new items to array-type column (Postgres)


Postgres supports array type columns, and exposes methods for working with those arrays (like array_append). I'm wondering if TypeORM allows using those methods somehow.

In case it's not supported, what do you think the best way to append items to PG array? Doing something like get-and-set? (a transaction of getting the value, creating the new new array with js, and updating the value in the DB)


Solution

  • You can use native Postgres methods like array_append if you use the TypeORM Query Builder.

    Example below:

    await dataSource.createQueryBuilder()
      .update(User)
      .set({
        yourArrayColumn: () => `array_append("yourArrayColumn", 1)`
      })
      .where("id = :id", { id: 1 })
      .execute();
    

    More about using TypeORM Query Builder for updates: https://typeorm.io/update-query-builder