Node.js Course
Node.js
/
Advanced

Repository Pattern

Definition

A design pattern that mediates between the domain (business logic) and data mapping layers using a collection-like interface for accessing domain objects.

Explain Like I'm New

It's an adapter for your database. Instead of writing `Mongoose.find()` or `SQL.execute()` directly inside your Controllers, you create a 'Repository' file. The Controller says 'Hey Repository, get me User 5'. The Controller has NO IDEA if the database is MongoDB, PostgreSQL, or a text file. The Repository handles the specific database code. If you switch from MongoDB to SQL tomorrow, you only change the Repository file. You don't have to rewrite 50 Controllers.

Real World Example

Enterprise applications where the underlying database technology might change, or where you want to easily create a 'Mock Repository' to run fast Unit Tests without a real database.

Common Use Cases

  • •Decoupling business logic from database logic
  • •Enterprise architectures

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is the main benefit of the Repository Pattern?

intermediate

  • Does the Controller know what type of database is being used?

Flash Cards

Question

Main benefit?

Click to reveal answer
Answer

Abstraction and Decoupling. It isolates your core application logic from the specifics of your database technology (like Mongoose or Sequelize).

Question

Does the Controller know?

Click to reveal answer
Answer

No. The Controller is completely agnostic. It just calls `userRepository.findById(123)`. It doesn't know or care if that data comes from SQL, Mongo, or an external API.