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

Build REST API with Mongoose & Express

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)
54 views5 pages

Build REST API with Mongoose & Express

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

Lab 09 – Combining REST API with Mongoose

Objective:
To guide students in building the backend of a task management system using [Link] 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 [Link] 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
[Link] 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 [Link].
3. Setup Express and MongoDB:

const express = require('express');


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

const app = express();


[Link]([Link]());

[Link]('mongodb://localhost:27017/taskdb', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => [Link]("MongoDB Connected"));

[Link](3000, () => [Link]("Server running on port 3000"));

Activity 2: Create a User Schema and Model

1. Create models/[Link]:

const mongoose = require('mongoose');

const userSchema = new [Link]({


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

[Link] = [Link]('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/[Link]:

const mongoose = require('mongoose');

const taskSchema = new [Link]({


title: { type: String, required: true },
description: String,
completed: { type: Boolean, default: false },
user: { type: [Link], ref: 'User' }
});

[Link] = [Link]('Task', taskSchema);

Activity 4: Add Routes to Create Users and Tasks

1. Create routes/[Link]:

const express = require('express');


const router = [Link]();
const User = require('../models/User');

[Link]('/users', async (req, res) => {


const user = await [Link]([Link]);
[Link](user);
});

[Link] = router;

2. Create routes/[Link]:

const express = require('express');


const router = [Link]();
const Task = require('../models/Task');

[Link]('/tasks', async (req, res) => {


const task = await [Link]([Link]);
[Link](task);
});

[Link] = router;

3. In [Link], register routes:

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


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

[Link](userRoutes);
[Link](taskRoutes);
Activity 5: View All Tasks with User Info (populate)

1. Add route in [Link]:

[Link]('/tasks', async (req, res) => {


const tasks = await [Link]().populate('user');
[Link](tasks);
});

Activity 6: Update Task Completion Status


[Link]('/tasks/:id', async (req, res) => {
const task = await [Link]([Link], { completed:
[Link] }, { new: true });
[Link](task);
});

Activity 7: Delete a Task


[Link]('/tasks/:id', async (req, res) => {
await [Link]([Link]);
[Link]("Task deleted.");
});

Activity 8: Validate Required Fields and Handle Errors

1. Wrap create logic in try/catch:

[Link]('/tasks', async (req, res) => {


try {
const task = await [Link]([Link]);
[Link](task);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

Activity 9: Add Timestamps and Virtuals (Optional)


const taskSchema = new [Link]({
title: String,
user: { type: [Link], ref: 'User' }
}, { timestamps: true });

Activity 10: Use Query Parameters to Filter Tasks


[Link]('/filter', async (req, res) => {
const completed = [Link] === 'true';
const tasks = await [Link]({ completed }).populate('user');
[Link](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 [Link] 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: [Link])
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