This repository contains a comprehensive tutorial on data modeling in Node.js using Mongoose. It covers simple, medium, and hard examples to help you understand how to structure your backend data efficiently.
Data modeling is the process of defining how data is stored, structured, and related in a database. It ensures consistency, efficiency, and easy querying.
A simple schema with basic fields:
import mongoose from "mongoose";
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
const User = mongoose.model("User", userSchema);
export default User;✅ Features:
- Basic fields (name, email, password)
- Validation (required, unique)
Includes relationships:
import mongoose from "mongoose";
import User from "./User.js";
const postSchema = new mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
tags: [String],
}, { timestamps: true });
const Post = mongoose.model("Post", postSchema);
export default Post;✅ Features:
- Relationship (author references User)
- Array (tags)
- Timestamps (createdAt, updatedAt)
- Complex schema with nested objects, enums, and multiple references:
import mongoose from "mongoose";
import User from "./User.js";
import Product from "./Product.js";
const orderSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
products: [
{
product: { type: mongoose.Schema.Types.ObjectId, ref: "Product", required: true },
quantity: { type: Number, required: true, default: 1 },
},
],
status: { type: String, enum: ["Pending", "Shipped", "Delivered"], default: "Pending" },
totalAmount: { type: Number, required: true },
shippingAddress: {
street: String,
city: String,
zip: String,
country: String,
},
}, { timestamps: true });
const Order = mongoose.model("Order", orderSchema);
export default Order;✅ Features:
- Multiple relationships (user and products)
- Array of objects (products)
- Nested objects (shippingAddress)
- Enum validation (status)
- Timestamps