How do insert multiple entities and return them in TypeORM

Viewed 6458

Let's say i have a Vote entity. I want to insert an array with 5 votes simultaneously and return them. I have tried : await Vote.save(votes) but that doesnt work and it doesnt return them either. Any ideas?

1 Answers

Firstly you need to prepare entities instances (it's not just an object which you mast probably have made in some place):

const votesEntities = Vote.create(votes);

And then you could save these entities:

await Vote.save(votesEntities);

But I would advise to use an insert instead of save (because save forms a separate query to DB for each entity) and return previously prepared entities. How it might look in the end:

async insertVotes(votes) {
  const votesEntities = Vote.create(votes);
  await Vote.insert(votesEntities);
  return votesEntities;
} 
Related