Create the User Mongoose Model

Create src/models/user.model.js.

A Mongoose schema defines the structure and behavior of documents stored in a collection.

For our application, a user will contain:

  • name
  • email
  • password
  • age
  • role
  • isActive
  • createdAt
  • updatedAt

The email should be unique, and the password should be excluded from ordinary query results by default.

Mongoose timestamps automatically manage createdAt and updatedAt.

Unique Is an Index, Not a Validator

The unique option creates a unique index. Duplicate email registration can produce a MongoDB duplicate-key error. Handle that error explicitly in your service or centralized error handler.

src/models/user.model.js
import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    minlength: 2,
    maxlength: 80
  },
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
    trim: true
  },
  password: {
    type: String,
    required: true,
    select: false
  },
  age: {
    type: Number,
    min: 18,
    max: 120
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user'
  },
  isActive: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

export const User = mongoose.model('User', userSchema);

Defines the user schema with field types, constraints, defaults, a unique email index declaration, and automatic timestamps.

Key Takeaways
  • Mongoose schemas define document structures.

  • Schema options support validation and default values.

  • The timestamps option manages createdAt and updatedAt.

  • The unique option creates a database index.