Lab10 - REST API with db
Lab10 - REST API with db
Objective:
To guide students in building the backend of a task management system using Express.js and
Mongoose. This lab helps students understand database integration, schema creation,
validation, and data relationships.
Activity Outcomes:
2. Create server.js.
3. Setup Express and MongoDB:
mongoose.connect('mongodb://localhost:27017/taskdb', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log("MongoDB Connected"));
1. Create models/User.js:
1. Create models/Task.js:
1. Create routes/user.js:
module.exports = router;
2. Create routes/task.js:
module.exports = router;
app.use(userRoutes);
app.use(taskRoutes);
Activity 5: View All Tasks with User Info (populate)
Lab Task 1: Extend Product Catalog API from previous lab to add
backend functionality with Mongoose.
You have already created a basic Product Catalog API using Express.js in the previous lab.
Now, extend that API by integrating MongoDB with Mongoose.
Perform the following tasks:
1. Setup MongoDB & Mongoose
o Install mongoose in your project using npm install mongoose.
o Connect your API to a local MongoDB instance or MongoDB Atlas.
2. Create a Mongoose Schema for Products
Your product model should include:
o name (String, required)
o price (Number, required)
o category (String)
o inStock (Boolean, default: true)
o createdAt (Date, default: Date.now)
3. Implement CRUD Functionality
o Create a new product (POST /products)
o Read all products (GET /products)
o Read a product by ID (GET /products/:id)
o Update a product by ID (PUT /products/:id)
o Delete a product by ID (DELETE /products/:id)
4. Validate Data
o Ensure products cannot be created without a name or price.
o Return appropriate HTTP status codes and error messages.
5. Test Using Postman
o Use Postman (or any REST client) to test all endpoints.
o Check both successful operations and validation errors.