乐闻世界logo
搜索文章和话题

What is Mongoose Schema and how to define and use it?

2月22日 20:12

Mongoose Schema is a core concept in Mongoose used to define the structure, data types, validation rules, and default values of MongoDB documents. Schema itself is not a collection in the database, but a blueprint used to create Models.

Basic Schema Definition

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: { type: String, required: true, trim: true }, email: { type: String, required: true, unique: true, lowercase: true, trim: true }, age: { type: Number, min: 0, max: 120 }, createdAt: { type: Date, default: Date.now } });

Main Schema Properties

  1. Field Types: String, Number, Date, Buffer, Boolean, Mixed, ObjectId, Array
  2. Validators: required, min, max, enum, match, validate
  3. Modifiers: lowercase, uppercase, trim, default
  4. Indexes: unique, sparse, index
  5. Virtual Fields: Computed fields not stored in database
  6. Instance Methods: Methods added to document instances
  7. Static Methods: Methods added to model classes
  8. Middleware: pre and post hooks

Relationship Between Schema and Model

  • Schema is the definition, Model is the constructor
  • Create Model via mongoose.model('User', userSchema)
  • Model instances are Documents, representing actual documents in the database
  • One Schema can create multiple Models (not recommended)

Schema Advantages

  1. Data Consistency: Enforce consistent document structure
  2. Data Validation: Validate data at application layer
  3. Type Safety: Provide type checking and conversion
  4. Middleware Support: Execute logic before/after operations
  5. Extensibility: Add methods and virtual fields
标签:Mongoose