Member-only story
Let’s Build a MERN Stack E-Commerce Web App
Part 2: Designing the Models
In the second part, we will design all the required models using Mongoose to connect to the MongoDB database with our Express App.
Hello friends! So, this is the second part of the MERN Stack series we have recently started. In the first part, we all learnt how to set up the project and had explanations about various things we were going to use in the project.
If you have not read the first part yet, here is the link to the first part:-
In the second part, we will start building models for our application. We are using MongoDB as the database to store all our data. We will use Mongoose to connect to the MongoDB database and it would make our work easier to build Database Schema and then the models based on that schema.
To keep things clean and simple, we would create a new folder named models in our root folder.
We will then create four files inside it which would represent our four models — User, Item, Cart and Order.
Note: We do not need to give a unique id parameter to our schemas since MongoDB automatically provides a unique ID once we save any document in it.
So, we will now go into the details of each model one by one. Let’s start with the User model.
User Model
So, we will now create our first model —the User Model. This would define the model which would store the data of our users. We will start by creating a User.js file in the ‘models’ folder we created earlier.
So, we will start by first requiring mongoose in our file. We will also require an isEmail validator from the ‘validator’ dependency we installed in the first part.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { isEmail } = require('validator');