MongoDB Schemas

This guide will help you create MongoDB schemas for your Node.js application using Mongoose, specifically in the `Schemas.js` file located in the `src` directory.

Setup

Ensure your project structure includes a src directory. Inside src, you will create or edit the Schemas.js file where all MongoDB schemas will be defined.

Step 1: Initialize Mongoose and Schema

Open or create the Schemas.js file in your src directory and start by requiring Mongoose and initializing the Schema constructor:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

Step 2: Define Your Schemas

You can define multiple schemas in the same file. Here are examples of two schemas: User and Product.

User Schema

Define a schema for a user with fields for username, email, and password:

javascriptCopy codeconst productSchema = new Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
  description: { type: String, required: false }
});

const Product = mongoose rModel('Product', productSchema);

Step 3: Export Your Models

After defining your schemas, you can export them to be used elsewhere in your project:

module.exports = {
  User,
  Product
};

Conclusion

By placing all your schemas in one file, Schemas.js, you maintain a clean and organized codebase. This setup also makes it easier to manage your data models as your application grows.

Now your Schemas.js file is set up with basic user and product schemas, and you can start using these models in your application to interact with MongoDB.

Last updated