Jia jewelry database
To create a full backend for Jia Jewelry, we will use Node.js, Express.js, and MongoDB for a RESTful API that handles products, users, authentication, and orders.
Features of the Jia Jewelry Backend
- Products API: CRUD operations for jewelry products.
- User Authentication: JWT-based login/signup.
- Orders API: Users can place and view orders.
- MongoDB: Database for storing products and orders.
1. Setup the Project
Run these commands to create and set up the project:
mkdir jia-jewelry-backend
cd jia-jewelry-backend
npm init -y
npm install express mongoose dotenv cors body-parser jsonwebtoken bcryptjs nodemon
2. Create server.js
(Main Entry Point)
const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const cors = require("cors");
dotenv.config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.error("MongoDB Connection Error:", err));
// Routes
app.use("/api/products", require("./routes/productRoutes"));
app.use("/api/users", require("./routes/userRoutes"));
app.use("/api/orders", require("./routes/orderRoutes"));
// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
3. Create a .env
file for Environment Variables
MONGO_URI=mongodb+srv://your_username:your_password@cluster.mongodb.net/jia-jewelry
JWT_SECRET=your_secret_key
4. Define the Jewelry Product Model
Create a folder models/
and inside it, a file Product.js
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
image: { type: String, required: true },
category: { type: String, required: true }
});
module.exports = mongoose.model("Product", productSchema);
5. Create Product Routes
Create 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 });
}
});
// Add a new product
router.post("/", async (req, res) => {
const { name, description, price, image, category } = req.body;
const product = new Product({ name, description, price, image, category });
try {
const savedProduct = await product.save();
res.status(201).json(savedProduct);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
module.exports = router;
6. Create User Authentication
Create models/User.js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: String,
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
module.exports = mongoose.model("User", userSchema);
Create routes/userRoutes.js
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/User");
router.post("/register", async (req, res) => {
const { name, email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ name, email, password: hashedPassword });
try {
await user.save();
res.json({ message: "User registered successfully" });
} catch (error) {
res.status(400).json({ message: "Error registering user" });
}
});
router.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(400).json({ message: "User not found" });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: "Invalid credentials" });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.json({ token });
});
module.exports = router;
7. Create Order Model & Routes
Create models/Order.js
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
products: [{ productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product" }, quantity: Number }],
totalAmount: Number,
status: { type: String, default: "Pending" }
});
module.exports = mongoose.model("Order", orderSchema);
Create routes/orderRoutes.js
const express = require("express");
const router = express.Router();
const Order = require("../models/Order");
// Place an order
router.post("/", async (req, res) => {
const { userId, products, totalAmount } = req.body;
const order = new Order({ userId, products, totalAmount });
try {
await order.save();
res.status(201).json({ message: "Order placed successfully" });
} catch (error) {
res.status(400).json({ message: "Error placing order" });
}
});
// Get orders by user
router.get("/:userId", async (req, res) => {
try {
const orders = await Order.find({ userId: req.params.userId });
res.json(orders);
} catch (error) {
res.status(500).json({ message: "Error fetching orders" });
}
});
module.exports = router;
8. Running the Backend
- Make sure your MongoDB database is running (or use MongoDB Atlas).
- Start the server:
or use nodemon for automatic restart:node server.js
nodemon server.js
Frontend Connection
Your React or Angular frontend can connect to these APIs:
Example API Requests
- Get all products:
GET /api/products
- Register user:
POST /api/users/register
- Login user:
POST /api/users/login
- Place an order:
POST /api/orders
- Get orders:
GET /api/orders/:userId
Next Steps
- Add payment integration (Stripe or PayPal).
- Implement admin dashboard to manage products & orders.
- Add email notifications for orders.
Let me know if you need a frontend for this backend or if you want any modifications!
Comments
Post a Comment