Script Valley
MongoDB: Complete Course
Mongoose and Node.js IntegrationLesson 5.1

How to set up Mongoose and define schemas in Node.js

Mongoose installation, Schema definition, SchemaTypes, model creation, connecting to MongoDB, connection events, disconnect handling

Mongoose vs the native driver

Native driver vs Mongoose

Mongoose is an Object Document Mapper (ODM) for MongoDB. It sits on top of the native driver and adds schema enforcement, field-level validation, pre and post operation hooks, and a fluent query API. Use Mongoose when you want consistent document shapes and business logic at the model layer. Use the native driver for maximum flexibility or raw performance on schema-free data.

npm install mongoose
const mongoose = require('mongoose')

// Connect — always await this before handling any requests
await mongoose.connect(process.env.MONGO_URI)

// Define a schema with type constraints
const productSchema = new mongoose.Schema({
  name:     { type: String, required: true, trim: true },
  price:    { type: Number, min: 0, required: true },
  category: { type: String, enum: ['electronics', 'clothing', 'books'] },
  tags:     [String],
  inStock:  { type: Boolean, default: true },
  createdAt:{ type: Date, default: Date.now }
})

// Create model — collection name is auto-inferred as 'products'
const Product = mongoose.model('Product', productSchema)

// Listen for connection lifecycle events
mongoose.connection.on('error', err => console.error('DB error', err))
mongoose.connection.on('disconnected', () => console.warn('DB disconnected'))

Always call mongoose.connect() once at application startup and reuse the same connection across all requests. Mongoose maintains an internal connection pool so you never need to manage connections manually in route handlers. Use environment variables for the connection string — never hardcode credentials.

Up next

Mongoose validation: built-in and custom validators

Sign in to track progress