Mongoose Schemas, Models, and Virtuals
Learners will define Mongoose schemas with type, validation, and default options, create models, and add virtual properties.
What Is Mongoose?
Mongoose is an Object Document Mapper (ODM) for MongoDB and Node.js. It sits on top of the official MongoDB driver and adds a layer of abstraction: schemas for validating document structure, models for database interaction, middleware hooks for pre/post operation logic, and virtuals for computed fields. Mongoose is the most popular MongoDB library in the Node.js ecosystem and is especially productive for server applications with well-defined data models.
// Install Mongoose
// npm install mongoose
const mongoose = require('mongoose');
// Connect to MongoDB
await mongoose.connect(process.env.MONGODB_URI);
console.log('Mongoose connected to MongoDB');Defining a Schema
A Mongoose Schema defines the structure, types, and constraints of documents in a collection. Each key in the schema corresponds to a document field. You can specify type, required, default, min, max, enum, and many other validation options per field. Schemas are the single source of truth for your document structure in a Mongoose application.
const { Schema } = mongoose;
const userSchema = new Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
maxlength: 100
},
email: {
type: String,
required: true,
unique: true,
lowercase: true // automatically converts to lowercase before saving
},
age: {
type: Number,
min: [0, 'Age cannot be negative'],
max: 150
},
role: {
type: String,
enum: ['admin', 'user', 'guest'],
default: 'user'
},
createdAt: {
type: Date,
default: Date.now
}
});All lessons in this course
- Connecting With the Official Node.js Driver
- Mongoose Schemas, Models, and Virtuals
- Mongoose Queries, Chaining, and Lean Documents
- Mongoose Middleware: Pre and Post Hooks