Share
Explore

s23 CSD 3103 S3 Full Stack JavaScript

Table 1
Column 1
Column 2
1
· Lesson 13 – Setting up a MongoDB database · Lesson 14 – Building models with Mongoose · Practice Exercises
2.1 Create and manage Documents, Collections, and Databases 2.2 Develop CRUD based applications, that are capable of creating, reading, updating, and deleting Documents in MongoDB Collections 2.3 Write and execute MongoDB queries to retrieve select Documents of interest from a MongoDB Collection 2.4 Work with MongoDB cursors 2.5 Implement MongoDB indexes to improve efficiency of querying a MongoDB Collection 2.6 Utilize MongoDB's aggregation framework to group and process data from multiple MongoDB Documents
2
· Lesson 15 – Connecting controllers and models · Lesson 17 – Improving your data models · Practice Exercises · Assignment 2 due
2.1 Create and manage Documents, Collections, and Databases 2.2 Develop CRUD based applications, that are capable of creating, reading, updating, and deleting Documents in MongoDB Collections 2.3 Write and execute MongoDB queries to retrieve select Documents of interest from a MongoDB Collection 2.4 Work with MongoDB cursors 2.5 Implement MongoDB indexes to improve efficiency of querying a MongoDB Collection 2.6 Utilize MongoDB's aggregation framework to group and process data from multiple MongoDB Documents
3
· Lesson 18 – Building the user model · Lesson 19 – Creating and reading your models · Lesson 20 – Updating and deleting your models · Practice Exercises
2.1 Create and manage Documents, Collections, and Databases 2.2 Develop CRUD based applications, that are capable of creating, reading, updating, and deleting Documents in MongoDB Collections 2.3 Write and execute MongoDB queries to retrieve select Documents of interest from a MongoDB Collection 2.4 Work with MongoDB cursors 2.5 Implement MongoDB indexes to improve efficiency of querying a MongoDB Collection 2.6 Utilize MongoDB's aggregation framework to group and process data from multiple MongoDB Documents
There are no rows in this table
Lesson 13: Setting Up A MongoDB Database
Understand the basics of MongoDB, a popular NoSQL database, and learn how to set up a MongoDB database using Node.js. This exercise covers installation, creation, and management of MongoDB databases, and explains how to use MongoDB command line [3].
Lesson 14: Building Models with Mongoose
Learn to use Mongoose, an object-document mapper (ODM) for MongoDB and Node.js. Understand how to create, update, delete, and find records in a MongoDB database using Mongoose. This lesson further explains how to reference and embed documents, create new instances of models, and work with schemas for models [1].
Practice Exercises:
2.1 Create, manage, and delete documents, collections, and databases using Node.js and MongoDB.
2.2 Develop CRUD based applications capable of creating, reading, updating, and deleting documents in MongoDB collections.
2.3 Write and execute MongoDB queries to retrieve selected documents of interest from a MongoDB collection.
2.4 Understand and work with MongoDB cursors for managing large result sets.
2.5 Implement MongoDB indexes to improve the efficiency of querying a MongoDB collection.
2.6 Utilize MongoDB's aggregation framework to group and process data from multiple MongoDB documents.
Lesson 15: Connecting Controllers and Models
Learn how to connect controllers and models in a Node.js application using the Express.js framework. Understand the role of controllers in managing the data flow between the model and the view [2].
Lesson 17: Improving Your Data Models
Delve deeper into data modeling with Mongoose and MongoDB. Understand how to optimize your data models for better performance and scalability [1].
Repeat the practice exercises from Lesson 14.
Lesson 18: Building the User Model
Learn how to build a User model using Mongoose. Understand the significance of User models in managing user data and authentication [2].
Lesson 19: Creating and Reading Your Models
Learn how to create and read data models using Mongoose. Understand how Mongoose aids in managing complex relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB [1].
Lesson 20: Updating and Deleting Your Models
Understand the processes of updating and deleting data models using Mongoose. Learn how to write code for updating and deleting records in a MongoDB database [1].

References:


Before diving into the complete code, it's crucial to first understand the primary components that we'll be working with:

MongoDB: A NoSQL database
Mongoose: A MongoDB object modeling tool (or ODM) designed to work in an asynchronous environment. It provides a straightforward, schema-based solution to model your application data.
The following Node.js program demonstrates how to use Mongoose to connect to a MongoDB database, create a model (in this case, a User model), and perform basic CRUD (Create, Retrieve, Update, Delete) operations:
First, ensure that you have the necessary modules installed. You can do this by executing the following command in your terminal:
bashCopy code
npm install express mongoose

Here is the complete Node.js code:
javascriptCopy code
const mongoose = require('mongoose');
const express = require('express');
const app = express();

mongoose.connect('mongodb://localhost/testDB', {useNewUrlParser: true, useUnifiedTopology: true});

const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});

const User = mongoose.model('User', userSchema);

app.use(express.json());

app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
const savedUser = await user.save();
res.send(savedUser);
} catch (err) {
res.status(500).send(err);
}
});

app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.send(users);
} catch (err) {
res.status(500).send(err);
}
});

app.get('/users/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
res.send(user);
} catch (err) {
res.status(500).send(err);
}
});

app.patch('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, {new: true});
res.send(user);
} catch (err) {
res.status(500).send(err);
}
});

app.delete('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
res.send(user);
} catch (err) {
res.status(500).send(err);
}
});

app.listen(3000, () => console.log('Server is running on port 3000'));


This simple REST API allows you to perform the following actions:
POST a new user at /users endpoint
GET all users from /users endpoint
GET a specific user from /users/:id endpoint
PATCH (update) a specific user from /users/:id endpoint
DELETE a specific user from /users/:id endpoint
Please replace 'mongodb://localhost/testDB' with your own MongoDB connection string, and install MongoDB on your local system if it's not already installed. Note that this code should ideally have better error handling and validation, but for the sake of brevity and clarity, those aspects have been simplified.
[1] In MongoDB, you can use embedding to create parent-child relationships where a parent document has one or more child documents. You could also use referencing to create relationships between documents in different collections.

Add to the above code by providing a Node.js Program to send a request to the mongo database to print out all the database records and write them to an HTML page

Here's how you can modify the above program to get all users and render them to an HTML page using the EJS templating engine. First, install the necessary module (ejs) by executing the following command in your terminal:
bashCopy code
npm install ejs

Then, modify the Node.js program as follows:
javascriptCopy code
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const ejs = require('ejs');

mongoose.connect('mongodb://localhost/testDB', {useNewUrlParser: true, useUnifiedTopology: true});

const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});

const User = mongoose.model('User', userSchema);

app.set('view engine', 'ejs');
app.use(express.json());

// Your existing routes...

app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.render('users', { users: users });
} catch (err) {
res.status(500).send(err);
}
});

// Your existing routes...

app.listen(3000, () => console.log('Server is running on port 3000'));

You also need to create an EJS template file to display the user data. In the root of your project, create a new directory called views (if it doesn't already exist). Inside views, create a new file called users.ejs with the following content:
htmlCopy code
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>List of Users</h1>
<ul>
<% users.forEach(user => { %>
<li>
<h2><%= user.name %></h2>
<p>Age: <%= user.age %></p>
<p>Email: <%= user.email %></p>
</li>
<% }); %>
</ul>
</body>
</html>

Now, if you navigate to http://localhost:3000/users in your web browser, you'll see a list of all the users in the database.
Remember to replace 'mongodb://localhost/testDB' with your own MongoDB connection string and ensure MongoDB is installed on your local system.
Note: In a production setting, you would typically have additional security measures, error handling, and data validation. These have been omitted here for simplicity.

Now add another module to this lab in which on the HTML page which is generated by Express.js, there is a form which queries all the users in the MONGO DB database, and a dropdown list from which the user of the webpage can select one users to display detailed data on.


To add a form with a dropdown list of users and display details of a selected user, we will need to adjust our Express routes and EJS templates accordingly.
Firstly, let's modify the GET /users route to render a new view called userForm:
javascriptCopy code
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.render('userForm', { users: users });
} catch (err) {
res.status(500).send(err);
}
});

Next, we'll add a new route to handle the form submission:
javascriptCopy code
app.get('/user-details', async (req, res) => {
try {
const user = await User.findById(req.query.userId);
res.render('userDetails', { user: user });
} catch (err) {
res.status(500).send(err);
}
});

In the above route, req.query.userId contains the id of the selected user, which is sent as a query parameter in the GET request when the form is submitted.
Now, create the userForm.ejs file in your views directory:
htmlCopy code
<!DOCTYPE html>
<html>
<head>
<title>Select a User</title>
</head>
<body>
<h1>Select a User</h1>
<form action="/user-details" method="get">
<select name="userId">
<% users.forEach(user => { %>
<option value="<%= user._id %>"><%= user.name %></option>
<% }); %>
</select>
<input type="submit" value="Show Details">
</form>
</body>
</html>

In the above template, we create a form with a dropdown list of users. Each option in the dropdown has the user's id as the value and the user's name as the display text. When the form is submitted, a GET request is sent to the /user-details route with the selected user's id as a query parameter.
Finally, create the userDetails.ejs file in your views directory:
htmlCopy code
<!DOCTYPE html>
<html>
<head>
<title>User Details</title>
</head>
<body>
<h1>User Details</h1>
<p>Name: <%= user.name %></p>
<p>Age: <%= user.age %></p>
<p>Email: <%= user.email %></p>
</body>
</html>

In the above template, we display the details of the selected user.
Now, when you navigate to http://localhost:3000/users, you should see a form with a dropdown list of users. After selecting a user and submitting the form, you should be redirected to a page displaying the details of the selected user.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.