I’m doing a bulk insert using
repository.insert(...)
in TypeORM, and I’m trying to figure out the best way to associate inserted records with their related metadata for follow-up inserts in other tables.
Here’s the situation:
I’m inserting a list ofProduct
entities where each product has a uniquename
. I’m also maintaining aMap<string, { product, tags, locations }>
where the key is the product’s name, and the value includes all the related data that will be inserted into other tables (likeproduct_tags
,product_locations
, etc.) that depend on the generatedproductId
.
I use this code:
const productsToInsert = [...productMap.values()].map(entry => entry.product);
const insertResult = await dataSource.getRepository(Product).insert(productsToInsert);
insertResult.generatedMaps.forEach((p, idx) => {
// Trying to get the name to map back to productMap
const productName = p.name; // not available here
const id = p.id;
});
The issue is that
generatedMaps
only contains columns that were generated (e.g.,id
), and not columns likename
that were explicitly set. So I can’t match back the inserted ID with the original product usingname
, which was my key.>
Is there a better way to track which inserted ID belongs to which original entity when using.insert()
?
- I want to get the ids after insertion so i can map the ids with name and then insert in other tables too where we need this id for foreign key.