javascripttypeormnode.js-typeorm

Typeorm bulk insert entities with foreign key


I have the following typeorm code in a for loop:

const user = await User.create({
    name: 'bobby',
}).save()
await Post.create({
        title: 'test'
        userId: user.id,
      }).save();

I tried the following code but I get an error about user.id being null:

const user = User.create({
        name: 'bobby',
    })
const post = Post.create({
    title: 'test'
    userId: user.id,
}).save();
await Post.insert(post);
await User.insert(user);

Is there a way to solve this without outright creating a entity new table?


Solution

  • You have to successfully insert User before getting its id.
    To minimize the number of queries, you can create and insert an array of User then use that users' ids to create an array of Post and insert it.

    let arrayUser: User[] = [];
    for(let i=0; i<num; i++){
    
     // create new user
     const user1 = new User();
     user1.name = 'bobby';
     arrayUser.push(user1);
    }
    
    // insert new users
    const userRepo = AppDataSource.getRepository(User);
    await userRepo.insert(arrayUser);
    
    
    let arrayPost: Post[] = [];
    for(let i=0; i<num; i++){
    
     // create new post
     const post1 = new Post();
     post1.title = 'test';
     post1.userId = arrayUser[i].id;
     // maybe better if you use relation: post1.user = arrayUser[i];
    
     arrayPost.push(post1);
    }
    
    // insert new posts
    const postRepo = AppDataSource.getRepository(Post);
    await postRepo.insert(arrayPost);