Database Strategy

How your database is structured determines how your API performs. In REST, we often model our database to match our Resources.

1. Serialization (Clean Output)

Your database schema isn't your API response. Never return your entire DB object.

// ❌ Bad: Returns passwordHash, privateEmail, __v
      res.json(user);

      // ✅ Good: Transform the object before sending
      const output = {
        id: user._id,
        username: user.username,
        member_since: user.createdAt
      };
      res.json({ data: output });

2. Normalization vs Embedding

  • SQL Approach: Normalize data and use JOINs. Great for data integrity.
  • NoSQL Approach: Embed related data (e.g., embedding tags in a post). Great for read speed.

3. Indexing for API Queries

If your API allows filtering (e.g., /products?category=electronics), you must have a database index on the category field. Without it, your API will slow down exponentially as users grow.

4. The Data Access Layer (DAL)

Avoid calling database methods (like Model.find) directly in controllers. Create a data layer so you can mock the database during unit testing.

Security Warning: Always use an Allow-list for fields. Accidentally returning password_hash or reset_tokenis one of the most common API security breaches.