📚

Creating MongoDB Models with Mongoose

Aug 31, 2024

M Stack Tutorial Part 12 - MongoDB Models with Mongoose

Overview

  • This session focuses on creating a simple model in Express.js using Mongoose.
  • Previous session recap: Created a controller and migrated API logic from route.js to a controller file.

Key Concepts

What is a Schema?

  • Defines the structure of documents in a collection.
  • Specifies fields, data types, validation, etc.
  • Schema was previously created using MongoDB Cluster.

What is a Model?

  • A compiled version of a schema.
  • Responsible for creating and reading documents from the MongoDB database.

Steps to Create a MongoDB Model with Mongoose

  1. Install Mongoose Package
    • Use command: npm install mongoose
  2. Connect to MongoDB
    • Set up a connection (to be done later in the session).
  3. Define a Schema
    • Represent the structure of documents.
  4. Compile Schema into a Model
    • Use the defined schema in the application.

Coding Steps

  1. Create Models Folder

    • In Visual Studio, create a folder named models.
  2. Create user.js Model

    • File represents the users collection.
    • Define schema with properties: email, first name, last name.
    • Set property type as String.
  3. Wrap Schema in Schema Object

    • Import Mongoose with: const mongoose = require('mongoose');
    • Define schema: const Schema = mongoose.Schema;
    • Create User Schema: const userSchema = new Schema({...});
  4. Add Properties

    • Example: Make email property required: email: { type: String, required: true }.
  5. Export User Schema

    • Create model: const User = mongoose.model('User', userSchema);
    • Export: module.exports = User;

Tools for Schema Generation

  • Transformation tools available to convert JSON to Mongoose schema.
  • Copy the existing user collection in JSON format and paste it into the tool.
  • The output schema can be copied into the Visual Studio solution.

Next Session

  • Focus on connecting the Mongoose model and updating the database using model files.