Lab04 - Node.js MongoDB
Lab04 - Node.js MongoDB
JS MONGODB
UNIVERSITY OF INFORMATION TECHNOLOGY
1
4. NODE.JS MONGODB
A. OVERVIEW
1. Learning Objective
In this lab, students will be:
2. Background knowledge
a. MongoDB
2
have different fields. Typically, all documents in a collection are of similar
or related purpose.
Database Database
Table Collection
Tuple/Row Document
column Field
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
}
]
}
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).
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.
▪ 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.
5
Extract the Todo.zip and do requirements below.
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).
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.
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)
6
models/todo.js
▪ 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.
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))
In the routes/index.js, adjust the route GET / to show all tasks (retrieved from the
database)
7
1 ...
2 const TodoModel = require('../models/todo')
3 ...
4
5 TodoModel.find({}).then(function (tasks) {
6 // On successfully retrieving data
7 //
8 });
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.
▪ 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