DataLoader is a utility built into Orionjs MongoDB collections that helps solve the N+1 query problem and optimize database access patterns. It provides:
Batching: Combines multiple individual requests into a single database query
Caching: Avoids duplicate queries by caching results for the duration of a request
Consistent API: Simple methods for various loading patterns
Loads a single document by its ID with DataLoader caching and batching.
Copy
// Load a document by IDconst user = await this.users.loadById(userId)// Multiple loadById calls for the same ID will use cached resultsconst sameUser = await this.users.loadById(userId)
Loads a single document by any field with DataLoader caching and batching.
Copy
// Load a document by a specific fieldconst user = await this.users.loadOne({ key: 'email', // Field to query by value: 'user@example.com', // Value to match match: {isActive: true}, // Optional additional query filter sort: {createdAt: -1}, // Optional sorting project: {name: 1, email: 1}, // Optional projection timeout: 10, // Optional batch timeout in ms (default: 5) debug: false // Optional debug logging})