🌐 MERN backend template for e-commerce websites
- Download node from here
- Download git from here
- Install yarn
npm install --global yarn
- Get source code
git clone https://github.com/RobzLegz/e-commerce-backend backend
cd backend
- Install dependencies
yarn install
- Create .env file
touch .env
- Update .env file
PORT=
MONGODB_URL=
REFRESH_TOKEN_SECRET=
ACCESS_TOKEN_SECRET=
CLOUD_NAME=
CLOUD_API_KEY=
CLOUD_API_SECRET=
PORT
can be a random 4 digit number, I'd suggest 5000
Create a mongodb project by following this tutorial and update MONGODB_URL in .env file
You can create REFRESH_TOKEN_SECRET
and ACCESS_TOKEN_SECRET
by generating secure 50 character password here
CLOUD_NAME
& CLOUD_API_KEY
& CLOUD_API_SECRET
are accessible when You register to cloudinary
- run project
yarn dev
app.use("/api/user", userRouter); //http://localhost:5000/api/user
app.use("/api/categories", categoryRouter); //http://localhost:5000/api/categories
app.use("/api/upload", uploadRouter); //http://localhost:5000/api/upload
app.use("/api/products", productRouter); //http://localhost:5000/api/products
app.use("/api/orders", orderRouter); //http://localhost:5000/api/orders
const {name, email, phoneNumber, products, address, city, date} = req.body;
if(!name || !email || !phoneNumber || !products || !address || !city || !date){
return res.status(400).json({err: "Please fill in all fields"});
}
let total = 0;
let soldProductIds: string[] = [];
products
.filter((product: Product) => !soldProductIds.includes(product._id))
.forEach((product: Product) => {
if(!soldProductIds.includes(product._id)){
let quantity = products.filter((p: Product) => p._id === product._id).length;
total += (product.price * quantity);
soldProductIds.push(product._id);
sell(product._id, quantity, product.sold, product.stock);
}
});
const newOrder = new Orders({
name,
email,
phoneNumber,
products,
address,
city,
date,
total
});
await newOrder.save();
res.json({msg: "Order received, check Your email"});
const sell = async (id: string, quantity: number, oldSold: number, oldStock: number) => {
let newSold = oldSold + quantity;
let newQuantity = oldStock - quantity;
await Products.findByIdAndUpdate({_id: id}, {
sold: newSold,
stock: newQuantity,
});
}