MERN stack application of the e-commerce market place for product search
Making a MERN (MongoDB, Express.js, React, Node.js) stack app for an online store needs a backend for managing product info, user sign-in, and database interactions. Here's a simple example showing how to organize your app. Remember, this is just a basic example. In real life, you'd need to take care of security, user sign-in, permissions, and more.
Backend (Node.js with Express)
- Setting Up Express Server (
server.js
):
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const productRoutes = require('./routes/productRoutes');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.json());
// Connect to MongoDB Atlas
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.use('/api/products', productRoutes);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Product Routes (
routes/productRoutes.js
):
const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
// Get all products
router.get('/', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Other routes like create, update, delete, etc. can be added here
module.exports = router;
- Product Model (
models/Product.js
):
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number,
// Add more fields as needed
});
module.exports = mongoose.model('Product', productSchema);
Frontend (React)
- Create a React App:
npx create-react-app ecommerce-frontend
cd ecommerce-frontend
- Install Dependencies:
npm install axios
- Product Search Component (
src/components/ProductSearch.js
):
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const ProductSearch = () => {
const [products, setProducts] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
// Fetch products from the backend
axios.get('/api/products').then((response) => {
setProducts(response.data);
});
}, []);
const handleSearch = () => {
// Implement search logic based on searchTerm
const filteredProducts = products.filter((product) =>
product.name.toLowerCase().includes(searchTerm.toLowerCase())
);
console.log(filteredProducts);
};
return (
<div>
<input
type="text"
placeholder="Search products"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button onClick={handleSearch}>Search</button>
</div>
);
};
export default ProductSearch;
MongoDB Atlas
MongoDB Atlas is Atlas is a user-friendly cloud database service from MongoDB. It makes deploying, managing, and growing MongoDB databases simple. Here's how to begin:
Create a MongoDB Atlas Account:
- Go to the MongoDB Atlas website and sign up for an account.
Create a Cluster:
After logging in, click the "Build a Cluster" button.
Pick a cloud provider, region, and cluster setup. Follow the steps to make the cluster.
Configure Security Settings:
On the MongoDB Atlas dashboard, find the "Database Access" area.
Add a new database user with the right permissions.
Whitelist IP Address:
- In the "Network Access" area, put your IP address on the IP Whitelist.
Connect to Your Cluster:
Go to the "Clusters" area and click the "Connect" button for your cluster.
Follow the steps to connect with the MongoDB shell or a MongoDB driver.
Set Up Environment Variables:
- In your Node.js backend, save the connection string using environment variables. You can use a library like
dotenv
to handle environment variables.
- In your Node.js backend, save the connection string using environment variables. You can use a library like
// Example .env file
MONGODB_URI=mongodb+srv://<username>:<password>@<cluster-url>/<database>
- Be sure not to reveal private details, such as the connection string, in your code.
Connect the Node.js backend to the MongoDB Atlas:
- In your
server.js
file, change the MongoDB connection line to:
- In your
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
- Make sure the
MONGODB_URI
variable can be reached in your Node.js environment.
Deploy your application:
- Put your Node.js backend and React frontend on a hosting service (like Heroku, Netlify, or Vercel).
Don't forget to use good security practices, manage user authentication, and think about performance improvements for a real-world setup. This example gives a basic structure, but in a real situation, you'd probably add more features, handle errors, and increase security.