Mongoose Setup: Database Schemas & Models

🦁 Express.jsLesson 9Intermediate

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and translates between objects in code and database documents.

1 Connecting to MongoDB & Schema Setup

First, install Mongoose: npm install mongoose. Then write your DB setup and schema definitions:

JavaScript — models/User.js
const mongoose = require("mongoose");

// Establish MongoDB connection
mongoose.connect("mongodb://localhost:27017/expressdb")
  .then(() => console.log("Connected to MongoDB..."))
  .catch(err => console.error("Database connection error:", err));

// Define Schema model structure
const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true },
  role: { type: String, default: "user" },
  createdAt: { type: Date, default: Date.now }
});

// Compile schema into model export class
module.exports = mongoose.model("User", userSchema);
2 Code Challenge
Challenge: Create a Mongoose schema configuration for a Post model featuring properties title, body, and author, making the title property required.