Week 6 and 7 - Lectures Notes
Week 6 and 7 - Lectures Notes
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.
Installation:
In this section, we will connect the Express server to the MongoDB database using
Mongoose.
Steps:
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);
module.exports = db;
A schema defines the structure of the documents within a MongoDB collection, and a
model provides an interface to interact with the database.
Create a Model:
This Room model will allow us to interact with the rooms collection in the Hotel
database.
Once the connection and schema are set up, we will create API endpoints to interact
with the Hotel database.
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:
This ensures that incoming data in POST requests is parsed into JSON format.
We use try and catch blocks to handle errors during operations, such as interacting with
the database.
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.
This ensures that the code doesn't block the execution of other processes while waiting
for the database operation to complete.