Data Layer Architecture
Models & Database Schemas
Understanding the Mongoose user schema, role-based access control, indexing, and projection security.
1. User Schema Definition (`server/src/models/user.model.js`)
The User model manages identity, secure password hashes, and access privileges. It is strictly typed and indexed for high-volume reads:
User Model Schema
typescript
import mongoose from 'mongoose';
export interface IUser extends mongoose.Document {
name: string;
email: string;
password: string;
role: 'member' | 'admin';
createdAt: Date;
updatedAt: Date;
}
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
maxlength: 100
},
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
maxlength: 254,
index: true
},
password: {
type: String,
required: true,
select: false // Excluded by default from database queries
},
role: {
type: String,
enum: ['member', 'admin'],
default: 'member'
}
}, {
timestamps: true
});
export const User = mongoose.model('User', userSchema); 2. Schema Field Specifications
| Field | Type | Validation / Constraints | Description |
|---|---|---|---|
| name | String | Required, max 100 chars, trimmed | User display name rendered in the dashboard nav |
| String | Required, unique, lowercase, regex-checked | Login identifier, unique database index | |
| password | String | bcrypt hash (10 salt rounds), select: false | Never returned in API responses or user listings |
| role | String | Enum: ['member', 'admin'], default: 'member' | Enforces authorization boundaries via requireRole |
3. Security Invariants & Projections
Password Redaction
Database queries exclude password hashes by default. Controllers explicitly use projection safe helpers (getUserById) returning only _id, name, email, role, createdAt.
Role Protection
New registrations always default to member. Admin escalation cannot be passed via the request body during signup.