Setting Up the Project
Initial Setup:
mkdir node-express-api cd node-express-api npm init -y
Install Required Packages:
npm install express mongoose
Folder Structure
- node-express-api
- models
- controllers
- routes
- app.js
Models
1. User Model (models/user.js)
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
});
module.exports = mongoose.model('User', userSchema);
2. Product Model (models/product.js)
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: String,
price: Number,
category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
});
module.exports = mongoose.model('Product', productSchema);
3. Category Model (models/category.js)
const mongoose = require('mongoose');
const categorySchema = new mongoose.Schema({
name: String,
});
module.exports = mongoose.model('Category', categorySchema);
Controllers
1. User Controller (controllers/userController.js)
const User = require('../models/user');
exports.createUser = async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
2. Product Controller (controllers/productController.js)
const Product = require('../models/product');
exports.createProduct = async (req, res) => {
try {
const product = new Product(req.body);
await product.save();
res.status(201).json(product);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
3. Category Controller (controllers/categoryController.js)
const Category = require('../models/category');
exports.createCategory = async (req, res) => {
try {
const category = new Category(req.body);
await category.save();
res.status(201).json(category);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
Routes
Routes Setup (routes/index.js)
const express = require('express');
const userController = require('../controllers/userController');
const productController = require('../controllers/productController');
const categoryController = require('../controllers/categoryController');
const router = express.Router();
router.post('/users', userController.createUser);
router.post('/products', productController.createProduct);
router.post('/categories', categoryController.createCategory);
module.exports = router;
Bringing It All Together
app.js
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const app = express();
mongoose.connect('mongodb://localhost:27017/node-express-api', { useNewUrlParser: true, useUnifiedTopology: true });
app.use(express.json());
app.use('/api', routes);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Now, after setting up the above structure, you have the basic building blocks for an API in Node.js and Express. You can run the app with:
node app.js
Remember, this is a basic structure, and there's much more you can do, such as adding error handling, validation, authentication, etc. I hope this provides a solid starting point!