Day 2 May 15
6 Forms of JavaScript
Day 1 May 8
May 8 Activity A Lab Worksheet:
Watch this video on Service Oriented Architecture patterns:
Worksheet for setting up our Build tooling : MVSC and Node.js
Lucid Chart Visual Diagram:
Mind Map Visual Learning Roadmap:
Lecture Dictation
Course PowerPoint Workbook:
Lab Work Book:
The BOM and the COM
Last modified: Wednesday, 15 May 2024, 12:53 PM
Labs:
Week 5 June 3-7
THU June 6 s2 PM Session:
Today’s work is to introduce the backend persistence layer of our MVC Application.
To do this Assignment, you will need:
Express.js web server with Routes Setup (started)
Mongo DB Database
DONE:
Get setup with Node.js, NPMJS.com, and Visual Studio Code
TO DO:
done → Getting setup with Make an Account on MongoDB.com
Learn how to use JSON data storage in MONGO
Mongoose Code Drills: Learn how to do CRUD in package called MONGOOSE
Download LINK for MONGODB Server :
Lab Workbook: Introduction to JSON and MongoDB
1. What is JSON?
2. What is MongoDB.com?
3. Setting Up MongoDB Server
4. CRUD Operations with JSON in MongoDB
5. Mongoose Code Drills
6. Lab Exercises
---
1. What is JSON?
**JSON (JavaScript Object Notation)** is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is primarily used to transmit data between a server and a web application as text.
**Example JSON:**
```json
{
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30,
"skills": ["JavaScript", "Node.js", "MongoDB"]
}
```
**Key Features of JSON:**
- **Human-readable:** JSON is written in a readable format with key-value pairs.
- **Language-independent:** JSON is used across various programming languages.
- **Lightweight:** JSON files are smaller in size compared to XML.
### 2. What is MongoDB?
**MongoDB** is a NoSQL database that stores data in flexible, JSON-like documents. This makes data integration for certain types of applications faster and easier.
**Key Features of MongoDB:**
- **Schema-less:** MongoDB collections do not require their documents to have the same schema.
- **Scalable:** MongoDB scales horizontally using sharding.
- **Document-Oriented:** Data is stored in BSON format (Binary JSON).
### 3. Setting Up MongoDB
#### Step 1: Create a MongoDB Atlas Account
1. Visit [MongoDB Atlas](https://www.mongodb.com/cloud/atlas/register).
2. Sign up for a free account.
3. Follow the prompts to create your first cluster.
#### Step 2: Install MongoDB Compass
1. Download MongoDB Compass from [here](https://www.mongodb.com/products/compass).
2. Install MongoDB Compass and connect it to your MongoDB Atlas cluster.
#### Step 3: Install Node.js and NPM
1. Download and install Node.js from [nodejs.org](https://nodejs.org/).
2. Verify the installation by running:
```bash
node -v
npm -v
```
#### Step 4: Install Mongoose
1. Create a new project directory:
```bash
mkdir myMongoDBProject
cd myMongoDBProject
npm init -y
```
2. Install Mongoose:
```bash
npm install mongoose
```
### 4. CRUD Operations with JSON in MongoDB
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations you can perform on data in a database.
#### Create
Inserting new data into the database.
```json
{
"name": "Alice",
"email": "alice@example.com",
"age": 28,
"skills": ["Python", "Data Science"]
}
```
#### Read
Retrieving data from the database.
```json
[
{
"name": "Alice",
"email": "alice@example.com",
"age": 28,
"skills": ["Python", "Data Science"]
}
]
```
#### Update
Modifying existing data in the database.
```json
{
"name": "Alice",
"email": "alice.smith@example.com",
"age": 29,
"skills": ["Python", "Data Science", "Machine Learning"]
}
```
#### Delete
Removing data from the database.
```json
{
"name": "Alice"
}
```
### 5. Mongoose Code Drills
#### Setting Up Mongoose
Create a file named `app.js` and add the following content:
```javascript
const mongoose = require('mongoose');
// MongoDB Cloud URI
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority";
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB Cloud'))
.catch((err) => console.error('Connection error', err));
```
Replace `<username>` and `<password>` with your MongoDB Atlas credentials.
#### Define a Schema and Model
```javascript
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
skills: [String]
});
const User = mongoose.model('User', userSchema);
module.exports = User;
```
#### Create Operation
```javascript
const User = require('./models/user');
const createUser = async () => {
const user = new User({
name: 'John Doe',
email: 'john.doe@example.com',
age: 30,
skills: ['JavaScript', 'Node.js', 'MongoDB']
});
try {
const savedUser = await user.save();
console.log('User saved:', savedUser);
} catch (err) {
console.error('Error saving user:', err);
}
};
createUser();
```
#### Read Operation
```javascript
const User = require('./models/user');
const getUsers = async () => {
try {
const users = await User.find();
console.log('Users:', users);
} catch (err) {
console.error('Error getting users:', err);
}
};
getUsers();
```
#### Update Operation
```javascript
const User = require('./models/user');
const updateUser = async () => {
try {
const user = await User.findOne({ email: 'john.doe@example.com' });
if (user) {
user.age = 31;
const updatedUser = await user.save();
console.log('User updated:', updatedUser);
}
} catch (err) {
console.error('Error updating user:', err);
}
};
updateUser();
```
#### Delete Operation
```javascript
const User = require('./models/user');
const deleteUser = async () => {
try {
const user = await User.deleteOne({ email: 'john.doe@example.com' });
console.log('User deleted:', user);
} catch (err) {
console.error('Error deleting user:', err);
}
};
deleteUser();
```
### 6. Lab Exercises
#### Exercise 1: Setup and Connect to MongoDB
- Sign up for MongoDB Atlas and create a cluster.
- Connect to the cluster using MongoDB Compass.
#### Exercise 2: Create a Mongoose Model
- Define a schema for a new collection, e.g., `Product`.
- Create a model for the schema.
#### Exercise 3: Perform CRUD Operations
- Write scripts to perform Create, Read, Update, and Delete operations on the `Product` collection.
#### Exercise 4: Complex Queries and Aggregations
- Write scripts to perform complex queries, such as finding products within a price range or aggregating products by category.
#### Exercise 5: Data Validation and Middleware
- Implement data validation in your schema.
- Use Mongoose middleware to log operations.
### Conclusion
This lab workbook provides an introduction to JSON and MongoDB, guiding you through setting up MongoDB, using JSON for CRUD operations, and practicing with Mongoose code drills. By the end of these exercises, you should have a solid understanding of how to work with MongoDB and Mongoose in a Node.js environment.
Building the College Enrollment System with JSON in MONGODB
Lab Workbook: Introduction to JSON and MongoDB
Table of Contents
CRUD Operations with JSON in MongoDB 1. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is primarily used to transmit data between a server and a web application as text.
Example JSON:
{
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30,
"skills": ["JavaScript", "Node.js", "MongoDB"]
}
Key Features of JSON:
Human-readable: JSON is written in a readable format with key-value pairs. Language-independent: JSON is used across various programming languages. Lightweight: JSON files are smaller in size compared to XML. 2. What is MongoDB?