SyntaxStudy
Sign Up
MongoDB Mongoose Schemas and Models
MongoDB Beginner 1 min read

Mongoose Schemas and Models

Mongoose is an Object Document Mapper (ODM) for MongoDB and Node.js that provides schema-based modelling, type casting, validation, query building, and middleware hooks. You define a Schema that describes the shape and constraints of your documents, then compile the schema into a Model. The model provides the interface for creating, reading, updating, and deleting documents. Mongoose schemas support all MongoDB BSON types plus additional Mongoose-specific features such as virtual properties, custom validators, default values, and path-level indexes declared inline. Schemas can be nested and composed, making it easy to model complex document structures in a readable way.
Example
const mongoose = require('mongoose')

// Define a schema
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Name is required'],
    trim: true,
    minlength: 2,
    maxlength: 100
  },
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
    match: [/^\S+@\S+\.\S+$/, 'Invalid email format']
  },
  age: { type: Number, min: 0, max: 120 },
  role: { type: String, enum: ['user', 'admin', 'moderator'], default: 'user' },
  hobbies: [String],
  address: {
    city:    String,
    country: { type: String, default: 'US' }
  },
  createdAt: { type: Date, default: Date.now }
}, {
  timestamps: true   // adds createdAt and updatedAt automatically
})

// Virtual property — not stored in DB
userSchema.virtual('initials').get(function () {
  return this.name.split(' ').map(n => n[0]).join('').toUpperCase()
})

// Compile schema into a model
const User = mongoose.model('User', userSchema)
module.exports = User