Query Inside Loop (ARCH3064)
هذا المحتوى غير متوفر بلغتك بعد.
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.
Incorrect
Section titled “Incorrect”for (const id of productIds) { const stock = await stockRepo.findOneBy({ productId: id }); // query per iteration totals.push(stock?.quantity ?? 0);}Correct
Section titled “Correct”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.