Skip to content

Express-node-Begin-to-adavanace/Data-modling

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Data Modeling in Node.js with Mongoose

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.


What is Data Modeling?

Data modeling is the process of defining how data is stored, structured, and related in a database. It ensures consistency, efficiency, and easy querying.


1. Simple Example – User Schema

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)

2. Medium Example – Blog Post Schema

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)

3. Hard Example – E-commerce Order Schema

  • 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

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published