0% found this document useful (0 votes)
7 views

Week 6 and 7 - Lectures Notes

Uploaded by

superbyoy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week 6 and 7 - Lectures Notes

Uploaded by

superbyoy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

LECTURE NOTES: Week 6 and 7

1. Introduction to Mongoose Package

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It
provides a simple way to define schemas for your MongoDB collections and interact
with the database using models.

With Mongoose, we will:

 Connect the Express.js server to a MongoDB instance.


 Define schemas that outline the structure of our documents.
 Add validations to enforce data integrity.

Installation:

npm install mongoose

2. Connecting Express Server to MongoDB using Mongoose

In this section, we will connect the Express server to the MongoDB database using
Mongoose.

Steps:

1. Import Mongoose into your project:

const mongoose = require('mongoose');

2. Connect to MongoDB (the database name is "Hotel"):

const mongoURL = 'mongodb://localhost:27017/Hotel';


mongoose.connect(mongoURL);
const db = mongoose.connection;

3. Define Events
db.on(“connected”, ( )=>{console.log(“Connected to Database”);
db.on(“disconnected”, ( )=>{console.log(“Disonnected to Database”);
db.on(“error”, (error)=>{console.log(“Connection Error”, error);

4. Export Database Connection

module.exports = db;

3. Schema and Model using Mongoose

A schema defines the structure of the documents within a MongoDB collection, and a
model provides an interface to interact with the database.

Creating a Schema and Model

For our "Hotel" database, let’s create a Room schema.

const roomSchema = new mongoose.Schema({


roomNumber: {
type: Number,
required: true
},
type: {
type: String,
required: true,
enum: ['single', 'double', 'suite']
},
price: {
type: Number,
required: true
},
isAvailable: {
type: Boolean,
default: true
}
},{“collection”:”rooms”});

The schema defines the structure for each room:


 roomNumber is a required field of type Number.
 type is a required field with predefined values.
 price is a required field for the cost of the room.
 isAvailable indicates room availability with a default value of true.

Create a Model:

const Room = mongoose.model('Room', roomSchema);

This Room model will allow us to interact with the rooms collection in the Hotel
database.

4. Creating API Endpoints in Express (GET & POST)

Once the connection and schema are set up, we will create API endpoints to interact
with the Hotel database.

GET Endpoint to Fetch All Rooms

app.get('/rooms', async (req, res) => {


try {
const rooms = await Room.find();
res.status(200).json(rooms);
} catch (error) {
res.status(500).json({ message: error.message });
}
});

POST Endpoint to Add a New Room

app.post('/rooms', async (req, res) => {


const newRoom = new Room(req.body);
try {
const savedRoom = await newRoom.save();
res.status(201).json(savedRoom);
} catch (error) {
res.status(400).json({ message: error.message });
}
});

5. Using Bodyparser Middleware

Bodyparser helps in processing incoming request data before it reaches the server,
converting it into a format that is usable by our Express app (JSON format).

Install Bodyparser:

npm install body-parser

Use Bodyparser in the Express App:

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


app.use(bodyParser.json());

This ensures that incoming data in POST requests is parsed into JSON format.

6. Using Try and Catch for Error Handling

We use try and catch blocks to handle errors during operations, such as interacting with
the database.

Example (GET endpoint with error handling):

app.get('/rooms', async (req, res) => {


try {
const rooms = await Room.find();
res.status(200).json(rooms);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
In the example above, if an error occurs while retrieving the rooms, it will be caught in
the catch block, and a meaningful error message will be sent back to the client.

7. Using Async and Await for Database Operations

We should always use async and await when performing operations that involve
interaction with the database to ensure that the code runs asynchronously and non-
blocking.

Example (POST endpoint with async/await):

app.post('/rooms', async (req, res) => {


const newRoom = new Room(req.body);
try {
const savedRoom = await newRoom.save();
res.status(201).json(savedRoom);
} catch (error) {
res.status(400).json({ message: error.message });
}
});

This ensures that the code doesn't block the execution of other processes while waiting
for the database operation to complete.

You might also like