Lab 4. NODE.
JS MONGODB
UNIVERSITY OF INFORMATION TECHNOLOGY
1
4. NODE.JS MONGODB
A. OVERVIEW
1. Learning Objective
In this lab, students will be:
▪ Learning on permenant storing website's data into database (MongoDB).
▪ Create a simple Node.js application and the concept of routing,
middleware, template engines, and handing forms.
2. Background knowledge
a. MongoDB
MongoDB is a cross-platform, document-oriented database that provides, high
performance, high availability, and easy scalability. MongoDB works on concept
of collection and document.
▪ Database: A database is a physical container for collections. Each database
gets its own set of files on the file system. A single MongoDB server typically
has multiple databases.
▪ Collection: A collection is a group of MongoDB documents. It is the
equivalent of an RDBMS table. A collection exists within a single database.
Collections do not enforce a schema. Documents within a collection can
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
2
have different fields. Typically, all documents in a collection are of similar
or related purpose.
▪ Document: A document is a set of key-value pairs. Documents have
dynamic schema. Dynamic schema means that documents in the same
collection do not need to have the same set of fields or structure, and
common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS (Relational database
management system) terminology with MongoDB.
RDBMS (MySQL, Postgres, etc.) MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id provided
by MongoDB itself)
Following example shows the document structure of a blog site, which is simply
a comma separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'Apple MacBook Air Laptop',
description: '2020 Apple MacBook Air Laptop: Apple M1 Chip',
tags: ['Apple', 'Macbook', 'Laptop'],
price: 1000,
reviews: [
{
user:'user1',
message: 'Good',
dateCreated: new Date(2011,1,20,2,15),
rating: 4
}
]
}
For more information, visit https://tutorialspoint.com/mongodb/mongodb_overview.htm
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
3
B. LAB TASKS
1. Setup the MongoDB server
We will use MongoDB Atlas (https://cloud.mongodb.com/) cloud-hosted sandbox
database. You need to create an account with MongoDB (this is free).
After logging in, you’ll be taken to the home screen
Click the "Build a Database" button
Deploy the new database cluster with the following options:
▪ Template: M0 (free)
▪ Provider: AWS / Google Cloud / Azure
▪ Region: Prefer Singapore / HongKong / Tokyo
▪ Name: CSBU103
Security Quickstart
▪ How would you like to authenticate your connection: Username and
password.
▪ Provide the username and password combination for the new user
(managed by MongoDB). Remember to copy and store the credentials
safely as we will need them later on. Click the Create user button. You can
create multiple users.
Note: avoid using special characters in your MongoDB user password as
mongoose may not parse the connection string properly
▪ Where would you like to connect from: My local environment.
▪ Add entries to your IP Access List: Enter 0.0.0.0/0 in the IP Address field.
This tells MongoDB that we want to allow access from anywhere. Then
click the Add Entry button.
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
4
Note: It is a best practice to limit the IP addresses that can connect to your
database and other resources. Here we allow a connection from
anywhere because we don’t know where the request will come from after
deployment.
▪ Finally, click the Finish and Close button to perform cluster creation.
Open created clusster → Click the Connect button
▪ The Connect to Cluster screen will appear. Click the Drivers option under
the Connect to your application.
▪ You will now be shown the Connect screen
▪ DO NOT follow the step 2. Copy the connection string from the step 3 and
replace the username/password with the credentials that you created
before.
2. Develop a TODO application
In this task, we will build a simple to-do application with Nodejs using Express,
MongoDB (to store Todo’s in the database). In this application, users will be able
to create, delete and mark their tasks as done.
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
5
Extract the Todo.zip and do requirements below.
a. Establish database connection
To work with the database, you first need to create a connection. Firstly, you need
to install mongoose package as a MongoDB database driver. To install it, use the
following command inside your project folder:
npm install mongoose
Then, open app.js (in the root of your project) and copy the following text below
where you declare the Express application object (after the line const app =
express). Replace the database URL string ('insert_your_database_url_here') with
the location URL representing your own database (i.e. using the information from
MongoDB Atlas).
1 // Set up mongoose connection
2 const mongoose = require("mongoose");
3 mongoose.set("strictQuery", false);
4 const mongoDB = "insert_your_database_url_here";
5
6 main().catch((err) => console.log(err));
7 async function main() {
8 await mongoose.connect(mongoDB);
9 }
This code creates the default connection to the database and reports any errors to
the console.
Note that hard-coding database credentials in source code as shown above is not
recommended. We do it here because it shows the core connection code, and
because during development there is no significant risk that leaking these details
will expose or corrupt sensitive information.
Finally, start your application to make sure that the database connection be
established successfully.
b. Define the Todo Schema
We will define a separate module for each model. Start by creating a folder for our
models in the project root (/models) and then create a new file for Todo Schema
(/models/todo.js)
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
6
models/todo.js
1 const mongoose = require('mongoose');
2 const Schema = mongoose.Schema;
3
4 const TodoSchema = new Schema({
5 title: { type: String, required: true },
6 user: { type: String, required: true },
7 isDone: { type: Boolean},
8
9 });
10
11 // Export model
12 module.exports = mongoose.model("Todo", TodoSchema);
c. Create a new task
In the routes/index.js, create a new route
▪ GET /todo: Show the form for user enter the information for new task.
▪ POST /todo: Handle the submitted data, create new entry and store it into
database for new task. After successfully processed, redirect to /todo.
Below is a sample code to store new task into database:
1 ...
2 const TodoModel = require('../models/todo')
3 ...
4
5 let {title, user} = req.body
6 let newTodo = new TodoModel({title:title, user: user, isDone: 0})
7 newTodo.save()
8 .then(()=>{
9 console.log("New task is created")
10 })
.catch(err=>console.log(err))
d. List all tasks
In the routes/index.js, adjust the route GET / to show all tasks (retrieved from the
database)
Below is a sample code to retrieve all tasks from database:
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
7
1 ...
2 const TodoModel = require('../models/todo')
3 ...
4
5 TodoModel.find({}).then(function (tasks) {
6 // On successfully retrieving data
7 //
8 });
Deploy the Todo application with the following requirements:
▪ Listing all tasks
▪ Create new task
▪ Mark the specific task as done.
▪ Delete the specific task (optional)
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected] Lab 4. NODE.JS MONGODB
8
C. REQUIREMENTS AND SUBMISSION
You must complete all tasks in section B (Lab tasks). Advanced tasks are optional,
and you could get bonus points for completing those tasks. This lab is designed
for individuals. You have seven days to clear all tasks.
Your submission must meet the following requirements:
▪ Take a screenshot of your application/website.
▪ If the submission contains more than one file, you must place all
files/folders inside a folder whose name pattern is "StudentID-Name".
Then, archive this folder in the zip format.
Your submissions must be your own. You are free to discuss with other classmates
to find the solution. However, copying is prohibited, even if only a part of your
report. Both reports of the owner and the copier will be rejected. Please remember
to cite any source of the material (website, book, etc.) that influences your solution.
D. REFERENCES
1. W3Scholl Node.js MongoDB: https://www.w3schools.com/nodejs/nodejs_mongodb.asp
2. MongoDB Tutorial: https://www.tutorialspoint.com/mongodb/mongodb_overview.htm
University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2023
[email protected]