Ir al contenido

Query Inside Loop (ARCH3064)

Esta página aún no está disponible en tu idioma.

Key typescript.orm.query-inside-loop · Severity warning · Category orm

Issuing any DB read query (ad-hoc find, aggregate, repository call) inside a loop body produces a round-trip per item. Hoist the query out of the loop or fetch in bulk.

for (const id of productIds) {
const stock = await stockRepo.findOneBy({ productId: id }); // query per iteration
totals.push(stock?.quantity ?? 0);
}
const stocks = await stockRepo.find({ where: { productId: In(productIds) } });
const byId = new Map(stocks.map(s => [s.productId, s.quantity]));
const totals = productIds.map(id => byId.get(id) ?? 0);

Turn the per-iteration queries into a single bulk query (In/whereIn) and map results in memory.