Mongoose Schemas and Models
In Mongoose, **schemas** and **models** are the foundation. A schema defines the structure of your documents (like a blueprint), and a model is a compiled version of that schema that gives you methods to query and manipulate the data.
What is a Schema?
A schema defines the shape of documents within a collection. It specifies:
- Field names and their data types
- Whether a field is required
- Default values
- Validation rules
- Indexes
Think of a schema as a application form. It tells you what information to provide (name, email) and what format it should be in.
Schema Types
| Type | Description |
|---|---|
| String | Text data |
| Number | Integer or float |
| Date | Date and time |
| Boolean | True/false |
| Array | List of values |
| ObjectId | Reference to another document |
| Mixed | Any data type |
Creating a Schema
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Product name is required'], trim: true, maxlength: [100, 'Name cannot exceed 100 characters'] }, price: { type: Number, required: true, min: [0, 'Price cannot be negative'] }, category: { type: String, enum: ['electronics', 'books', 'clothing'], default: 'electronics' }, inStock: { type: Boolean, default: true }, tags: [String], details: { manufacturer: String, warranty: Number }, createdAt: { type: Date, default: Date.now }});Schema Options
You can pass options as a second argument:
const userSchema = new mongoose.Schema({ name: String, email: String}, { timestamps: true, <!-- Adds createdAt and updatedAt automatically --> versionKey: false, <!-- Removes __v field --> collection: 'myusers' <!-- Specify collection name -->});Creating a Model
A model is a class that we construct from a schema. Each instance of a model represents a document in the database.
const Product = mongoose.model('Product', productSchema);
<!-- Now you can use Product to interact with the 'products' collection -->Instance Methods
You can add custom methods to documents:
userSchema.methods.getFullProfile = function() { return `${this.name} (${this.email})`;};
const User = mongoose.model('User', userSchema);
<!-- Usage -->const user = new User({ name: 'John', email: 'john@example.com' });console.log(user.getFullProfile()); <!-- John (john@example.com) -->Static Methods
You can add static methods to the model itself:
userSchema.statics.findByEmail = async function(email) { return await this.findOne({ email });};
<!-- Usage -->const user = await User.findByEmail('john@example.com');Two Minute Drill
- A schema defines the structure of your documents – field types, validation, defaults.
- Mongoose supports various data types: String, Number, Date, Boolean, Array, ObjectId.
- A model is a compiled version of a schema that provides database operations.
- Use `mongoose.model('Name', schema)` to create a model.
- You can add instance methods (for documents) and static methods (for the model).
- Schema options like `timestamps` automatically add `createdAt` and `updatedAt`.
Need more clarification?
Drop us an email at career@quipoinfotech.com
