Schemas & Models

  • Schemas define the structure of data in MongoDB, while models are created from schemas to interact with the database using Mongoose.
  • Schema Definition

    A Schema defines the structure of a document in a MongoDB collection. It specifies fields, data types, validations, and rules that each document must follow.

    Why Schema is Important:

    • Enforces data consistency

    • Adds validation rules

    • Defines default values

    • Controls data shape

    Example – User Schema

Mongoose Schema Definition

A Mongoose schema defines the structure, data types, and validation rules for documents in a MongoDB collection. This example shows a user schema with required fields, unique constraints, and default values.

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    unique: true
  },
  age: Number,
  createdAt: {
    type: Date,
    default: Date.now
  }
});
  • Explanation:

    • type defines data type

    • required ensures value must be present

    • unique prevents duplicate values

    • default sets automatic values

    Model Creation

    A Model is a wrapper around a schema. It represents a MongoDB collection and is used to perform database operations like insert, find, update, and delete.

    Example – Creating a Model

Mongoose Model Creation

A Mongoose model is created from a schema and represents a MongoDB collection. It provides an interface to perform CRUD operations on the collection using JavaScript.

const User = mongoose.model("User", userSchema);
  • Explanation:

    • "User" becomes the collection name (users)

    • Model provides built-in CRUD methods

    • Each model instance represents a document

    Example – Using the Model

Using a Mongoose Model to Save Data

This code demonstrates how to create a new document using a Mongoose model and save it to the MongoDB collection with the save() method.

const newUser = new User({
  name: "Amit",
  email: "amit@gmail.com",
  age: 25
});

newUser.save();
  • Explanation:

    • Creates a new document

    • Saves data following schema rules