0% found this document useful (0 votes)
3 views5 pages

Lab10 - REST API with db

This document outlines a lab for students to build a task management system backend using Express.js and Mongoose. It includes objectives, activity outcomes, and step-by-step instructions for setting up a project, creating schemas, implementing CRUD operations, and validating data. Additionally, it provides graded tasks to extend a Product Catalog API with similar functionalities.

Uploaded by

amir.raza537918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Lab10 - REST API with db

This document outlines a lab for students to build a task management system backend using Express.js and Mongoose. It includes objectives, activity outcomes, and step-by-step instructions for setting up a project, creating schemas, implementing CRUD operations, and validating data. Additionally, it provides graded tasks to extend a Product Catalog API with similar functionalities.

Uploaded by

amir.raza537918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Lab 09 – Combining REST API with Mongoose

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:

By the end of this lab, students will be able to:

 Integrate MongoDB with an Express.js server using Mongoose.


 Create Mongoose models with schema validation.
 Build RESTful routes for basic CRUD operations.
 Establish relationships between collections (Users and Tasks).
 Use Mongoose’s populate() for querying related data.

1) Solved Lab Activites
Sr.No Allocated Time Level of Complexity CLO Mapping
1 10 Low CLO-5
2 10 Low CLO-5
3 10 Medium CLO-5
4 10 Medium CLO-5
5 10 Medium CLO-5
6 10 Medium CLO-5

Activity 1: Setup Project and Install Packages

1. Initialize your project (or create an express-generator app instead):

mkdir task-manager && cd task-manager


npm init -y
npm install express mongoose body-parser

2. Create server.js.
3. Setup Express and MongoDB:

const express = require('express');


const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();


app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/taskdb', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log("MongoDB Connected"));

app.listen(3000, () => console.log("Server running on port 3000"));

Activity 2: Create a User Schema and Model

1. Create models/User.js:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({


name: { type: String, required: true },
email: { type: String, required: true, unique: true }
});

module.exports = mongoose.model('User', userSchema);


You can create different files for all the models that you need in your project.

Activity 3: Create a Task Schema with Reference to User

1. Create models/Task.js:

const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({


title: { type: String, required: true },
description: String,
completed: { type: Boolean, default: false },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

module.exports = mongoose.model('Task', taskSchema);

Activity 4: Add Routes to Create Users and Tasks

1. Create routes/user.js:

const express = require('express');


const router = express.Router();
const User = require('../models/User');

router.post('/users', async (req, res) => {


const user = await User.create(req.body);
res.json(user);
});

module.exports = router;

2. Create routes/task.js:

const express = require('express');


const router = express.Router();
const Task = require('../models/Task');

router.post('/tasks', async (req, res) => {


const task = await Task.create(req.body);
res.json(task);
});

module.exports = router;

3. In server.js, register routes:

const userRoutes = require('./routes/user');


const taskRoutes = require('./routes/task');

app.use(userRoutes);
app.use(taskRoutes);
Activity 5: View All Tasks with User Info (populate)

1. Add route in task.js:

router.get('/tasks', async (req, res) => {


const tasks = await Task.find().populate('user');
res.json(tasks);
});

Activity 6: Update Task Completion Status


router.patch('/tasks/:id', async (req, res) => {
const task = await Task.findByIdAndUpdate(req.params.id, { completed:
req.body.completed }, { new: true });
res.json(task);
});

Activity 7: Delete a Task


router.delete('/tasks/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.send("Task deleted.");
});

Activity 8: Validate Required Fields and Handle Errors

1. Wrap create logic in try/catch:

router.post('/tasks', async (req, res) => {


try {
const task = await Task.create(req.body);
res.json(task);
} catch (err) {
res.status(400).json({ error: err.message });
}
});

Activity 9: Add Timestamps and Virtuals (Optional)


const taskSchema = new mongoose.Schema({
title: String,
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, { timestamps: true });

Activity 10: Use Query Parameters to Filter Tasks


router.get('/filter', async (req, res) => {
const completed = req.query.completed === 'true';
const tasks = await Task.find({ completed }).populate('user');
res.json(tasks);
});
2) Graded Lab Tasks

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.

You might also like