What is the N+1 query problem and how do you solve it in Node.js?

Answer

The N+1 query problem occurs when fetching a list of N records and then making one additional query per record to fetch related data — resulting in N+1 total queries instead of 1-2 efficient queries. Example: fetch 100 blog posts (1 query), then loop and fetch the author for each post (100 more queries) = 101 queries total. Solutions: (1) JOIN/populate in the initial query: fetch posts WITH author data in one query — SELECT posts.*, users.name FROM posts JOIN users ON posts.author_id = users.id or Mongoose Post.find().populate("author"); (2) Batch loading (DataLoader): the DataLoader library (by Facebook, used in GraphQL) batches individual lookups from multiple resolvers into a single query per event loop tick: const userLoader = new DataLoader(ids => User.findByIds(ids)); await userLoader.load(userId) — automatically batches parallel loads into one DB query; (3) Eager loading: in ORMs like Prisma/Sequelize, use include to load relations upfront; (4) Caching: cache frequently accessed lookup data in Redis.