Search code examples
databaseinsertgraphqltypeormbulk

Efficient way to bulk insert / update using typeORM


How it's possible to insert pre-created objects into relation with an object using TypeORM? As I know the non-efficient is this(many to many relations):

 const tags = await Tag.findByIds(tagIds);
 const todo = await Todo.findOne(todoId);
 todo.tags = tags;
 return await Todo.save(todo)

Also .add() property of RelationalQueryBuilder takes single object or Id as is mentioned in docs

await getConnection()
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(1)
    .add(3);

So what is the efficient way to bulk insert?


Solution

  • I had error while using @Arg imported from typeGraphql for passing an array of string so I resolved it so add() from typeOrm takes the Id array so the fast and performant example of relational query is:

    import { Resolver, Arg, Mutation } from "type-graphql";
    import { Todo } from "../../entity/Todo";
    import { createQueryBuilder } from "typeorm";
    
    @Resolver()
    export class BulkAssignTagsResolver {
      @Mutation(() => Todo)
      async bulkAssignTodoTag(
        @Arg("tagIds", () => [String]) tagIds: string[],
        @Arg("todoId") todoId: string
      ): Promise<Todo | undefined> {
        await createQueryBuilder("todo")
          .relation(Todo, "tags")
          .of(todoId)
          .add(tagIds);
    
        return Todo.findOne(todoId, { relations: ["tags"] });
      }
    }