Node.js › Architecture & Design Patterns
What is the Repository pattern, and how does it help decouple business logic from a specific database technology?
AdvancedAnswer
The Repository pattern defines an abstraction (an interface or a consistent set of functions) for accessing and persisting domain objects, hiding the specific database technology and query syntax behind that abstraction -- business logic calls methods like findById() or save() without knowing whether the underlying implementation uses MongoDB, PostgreSQL, or an in-memory store, which makes both testing (via a fake in-memory repository) and future database migrations significantly easier.
class UserRepository {
async findById(id) { return db.collection('users').findOne({ _id: id }); }
async save(user) { return db.collection('users').insertOne(user); }
}
// In tests, swap in a fake implementation with the same interface
class FakeUserRepository {
constructor() { this.users = new Map(); }
async findById(id) { return this.users.get(id); }
async save(user) { this.users.set(user.id, user); return user; }
}Real-world example A team migrating from MongoDB to PostgreSQL is able to complete the migration by rewriting only the internals of their UserRepository class, since every other part of the application only ever called repository.findById() and repository.save() and never issued raw queries directly.