Share
Explore

s24 Lesson Plan Full Stack Web Development TUE JUNE 4

1
Data Persistence
Continuation of Session 05
Insert a document
Update a document
Delete a document
Working with more than one collection (example: Employees and Vehicles, Books and Authors, etc)
MongoDB Documentation:
There are no rows in this table

Today’s Class is about CRUD and Predicate JOINS with MONGOOSE.


A simple example of Predicate Joins in MONGO JSON with the Aggregation Pipeline:

megaphone

Lab Topics:

Creating a MODEL
Creating a SCHEMA
MONGOOSE:
Insert a Document
Delete a Document
How do we do predicate Joins in MONGOOSE: Connecting Collections


1. Introduction to Node.js, NPM, and Visual Studio Code

Node.js: Review the basics of Node.js, its event-driven architecture, and its use for server-side scripting.
NPM: Describe NPM as the Node package manager, its role in managing dependencies, and how to use it to install packages.
Visual Studio Code (VS Code): VS Code is our NPM projects code editor, featuring IntelliSense, debugging, and integrated terminal.

2. Setting Up the Environment

Install Node.js and NPM: Demonstrate the installation process and verify the installation by running node -v and npm -v in the terminal.
Install VS Code: Review of VS Code, including setting up the Node.js environment.

3. Introduction to Mongoose and MongoDB

MongoDB: a NoSQL database which uses JSON documents for the data store.
Mongoose: Describe Mongoose as an ODM (Object Data Modeling) library for MongoDB and Node.js.

4. Creating a Model and Schema with Mongoose

Setting up the Project
Initialize a new Node.js project:
mkdir mongoose-demo
cd mongoose-demo
npm init -y

Install Mongoose:
npm install mongoose

Connecting to MongoDB via MONGO Db in the Cloud.
Create a file index.js:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Connection error', err);
});

Creating a Schema and Model
Define a schema and model for a User:
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});

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

Inserting a Document
Insert a new user document:
const createUser = async () => {
const user = new User({
name: 'John Doe',
email: 'john.doe@example.com',
age: 30
});

try {
const savedUser = await user.save();
console.log('User saved:', savedUser);
} catch (err) {
console.error('Error saving user:', err);
}
};

createUser();

Deleting a Document
Delete a user document by email:
const deleteUser = async (email) => {
try {
const result = await User.deleteOne({ email: email });
console.log('User deleted:', result);
} catch (err) {
console.error('Error deleting user:', err);
}
};

deleteUser('john.doe@example.com');

5. Predicate Joins in Mongoose: Connecting Collections

Defining Related Schemas
Define schemas for User and Post:
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

const Post = mongoose.model('Post', postSchema);

Creating References
Insert a post document that references a user:
const createPost = async () => {
const user = await User.findOne({ email: 'john.doe@example.com' });

const post = new Post({
title: 'My First Post',
content: 'This is the content of my first post',
author: user._id
});

try {
const savedPost = await post.save();
console.log('Post saved:', savedPost);
} catch (err) {
console.error('Error saving post:', err);
}
};

createPost();

Performing a Join
Query posts and populate the author field:
const getPosts = async () => {
try {
const posts = await Post.find().populate('author');
console.log('Posts:', posts);
} catch (err) {
console.error('Error fetching posts:', err);
}
};

getPosts();


Introduction to the Unified Earth Space Exploration Command (UESEC) Lab

Welcome to the Unified Earth Space Exploration Command (UESEC) Lab, an innovative and exciting initiative designed to engage in the creation and management of software systems that will power humanity's next great leap into the cosmos.
As a part of this groundbreaking project, you will be developing the crucial software infrastructure needed to support the operations and logistics of the newly formed UESEC.

About the Unified Earth Space Exploration Command

The Unified Earth Space Exploration Command (UESEC) is a visionary organization established with the mission of exploring the far reaches of our galaxy and beyond.
Comprised of top scientists, engineers, and explorers from around the globe, UESEC aims to push the boundaries of human knowledge and presence in space.
Our fleet of advanced starships is tasked with investigating distant star systems, discovering new forms of life, and forging a path for humanity among the stars.

Your Mission

As part of this lab, you will play a pivotal role in developing the software systems that will support UESEC's operations.
Your mission includes:
Database Management: Design and implement robust database systems using MongoDB and Mongoose to store and manage critical data on starships, crew members, missions, and more.
Crew Assignment Algorithms: Develop intelligent algorithms to match crew members to starships based on their skills and the specific needs of each mission.
Operational Dashboards: Create dynamic dashboards to monitor the status of starships, crew rosters, mission progress, and other key metrics.
Automation Tools: Build automation tools to streamline various operational processes, from crew assignments to mission planning and logistics.

Lab Objectives

By the end of this lab, you will have:
Mastered MongoDB and Mongoose: Gained hands-on experience in working with NoSQL databases and the Mongoose ODM to manage complex datasets.
Developed Matching Algorithms: Created sophisticated algorithms to efficiently assign crew members to starships based on mission requirements and crew specialties.
Built Interactive Dashboards: Designed and implemented interactive dashboards that provide real-time insights into UESEC operations.
Enhanced Problem-Solving Skills: Sharpened your problem-solving abilities by tackling real-world challenges in space exploration logistics and management.

Project Workflow

Data Insertion: Start by inserting sample data into the MongoDB database, including details about crew members and starships.
Crew Assignment: Write code to assign crew members to starships based on their skills and the needs of each mission.
Display Crew Manifest: Develop features to display crew manifests for each starship, showcasing the assignments and readiness of the crew.
Optimization and Automation: Implement advanced features to optimize crew assignments and automate routine tasks.

Getting Started

Insert Crew Members: Use the provided insertCrewMembers.js script to populate the database with a diverse roster of crew members, each with unique specialties essential for space exploration.
Insert Starships: Run the insertStarships.js script to add details of the UESEC starships, including their destinations and the technical specialties required for their missions.
Assign Crew to Starships: Execute the assignCrewToStarships.js script to intelligently assign crew members to the starships based on their skills and the needs of each mission.
Display Crew Manifest: Use the displayCrewManifest.js script to generate and display the crew manifests, ensuring that each starship is properly staffed and ready for its mission.

Conclusion

This lab is not just an exercise in software development; it is a simulation of the critical role you will play in the future of space exploration. Your work here will lay the foundation for the software systems that will support humanity's journey to the stars. Embrace the challenge, apply your skills, and contribute to the mission of the Unified Earth Space Exploration Command.
Together, we will explore the final frontier. Welcome aboard, cadets!
megaphone

United Earth Space Force

image.png
Mission Outcome:
Create a program that inserts crew members into a MongoDB collection with the added specialty field.

Step 1: Create the Text File with Sample Records

Create a text file named `crewMembers.txt` with 100 sample records:

```
John Doe,john.doe@example.com,Astrobiology
Jane Smith,jane.smith@example.com,Exobiology
James Brown,james.brown@example.com,Xenobiology
Mary Johnson,mary.johnson@example.com,Astrochemistry
Robert Jones,robert.jones@example.com,Molecular engineering
Linda Davis,linda.davis@example.com,Metamaterials
Michael Wilson,michael.wilson@example.com,Programmable matter
Sarah Miller,sarah.miller@example.com,Psionic technology
David Martinez,david.martinez@example.com,Dimensional manipulation
Laura Garcia,laura.garcia@example.com,Consciousness interfacing
Kevin Anderson,kevin.anderson@example.com,Xenoarchaeology
Karen Thomas,karen.thomas@example.com,Quantum computing
Matthew Jackson,matthew.jackson@example.com,Transwarp propulsion
Patricia White,patricia.white@example.com,Terraforming
Daniel Harris,daniel.harris@example.com,Xenolinguistics
Barbara Clark,barbara.clark@example.com,Astrobiology
Paul Lewis,paul.lewis@example.com,Exobiology
Nancy Robinson,nancy.robinson@example.com,Xenobiology
Mark Walker,mark.walker@example.com,Astrochemistry
Sandra Young,sandra.young@example.com,Molecular engineering
John Smith,john.smith@example.com,Metamaterials
Lisa Johnson,lisa.johnson@example.com,Programmable matter
James White,james.white@example.com,Psionic technology
Michael Brown,michael.brown@example.com,Dimensional manipulation
Emily Davis,emily.davis@example.com,Consciousness interfacing
David Wilson,david.wilson@example.com,Xenoarchaeology
Sarah Martinez,sarah.martinez@example.com,Quantum computing
Jessica Lee,jessica.lee@example.com,Transwarp propulsion
Daniel Anderson,daniel.anderson@example.com,Terraforming
Laura Thomas,laura.thomas@example.com,Xenolinguistics
Nancy Jackson,nancy.jackson@example.com,Astrobiology
Paul Walker,paul.walker@example.com,Exobiology
Karen Lewis,karen.lewis@example.com,Xenobiology
Sandra Harris,sandra.harris@example.com,Astrochemistry
Emily Clark,emily.clark@example.com,Molecular engineering
James Robinson,james.robinson@example.com,Metamaterials
Michael Young,michael.young@example.com,Programmable matter
Linda Jackson,linda.jackson@example.com,Psionic technology
Barbara Lee,barbara.lee@example.com,Dimensional manipulation
Mark Davis,mark.davis@example.com,Consciousness interfacing
Kevin Martinez,kevin.martinez@example.com,Xenoarchaeology
Lisa Brown,lisa.brown@example.com,Quantum computing
Patricia White,patricia.white@example.com,Transwarp propulsion
John Harris,john.harris@example.com,Terraforming
David Clark,david.clark@example.com,Xenolinguistics
James Walker,james.walker@example.com,Astrobiology
Michael Martinez,michael.martinez@example.com,Exobiology
Nancy Davis,nancy.davis@example.com,Xenobiology
Linda Lee,linda.lee@example.com,Astrochemistry
Paul Brown,paul.brown@example.com,Molecular engineering
Barbara Wilson,barbara.wilson@example.com,Metamaterials
David Johnson,david.johnson@example.com,Programmable matter
Sarah Smith,sarah.smith@example.com,Psionic technology
Jessica Harris,jessica.harris@example.com,Dimensional manipulation
Daniel Clark,daniel.clark@example.com,Consciousness interfacing
John Lewis,john.lewis@example.com,Xenoarchaeology
Kevin White,kevin.white@example.com,Quantum computing
Laura Robinson,laura.robinson@example.com,Transwarp propulsion
Michael Anderson,michael.anderson@example.com,Terraforming
Nancy Martinez,nancy.martinez@example.com,Xenolinguistics
James Harris,james.harris@example.com,Astrobiology
Sandra Johnson,sandra.johnson@example.com,Exobiology
David Lee,david.lee@example.com,Xenobiology
Karen Walker,karen.walker@example.com,Astrochemistry
Paul Young,paul.young@example.com,Molecular engineering
Barbara Martinez,barbara.martinez@example.com,Metamaterials
Kevin Jackson,kevin.jackson@example.com,Programmable matter
Sarah Robinson,sarah.robinson@example.com,Psionic technology
James Brown,james.brown@example.com,Dimensional manipulation
Linda Harris,linda.harris@example.com,Consciousness interfacing
Mark Clark,mark.clark@example.com,Xenoarchaeology
Nancy Smith,nancy.smith@example.com,Quantum computing
John Davis,john.davis@example.com,Transwarp propulsion
Jessica Martinez,jessica.martinez@example.com,Terraforming
Kevin Johnson,kevin.johnson@example.com,Xenolinguistics
David White,david.white@example.com,Astrobiology
Emily Brown,emily.brown@example.com,Exobiology
Paul Martinez,paul.martinez@example.com,Xenobiology
Sandra Lee,sandra.lee@example.com,Astrochemistry
Michael Jackson,michael.jackson@example.com,Molecular engineering
Linda White,linda.white@example.com,Metamaterials
Barbara Johnson,barbara.johnson@example.com,Programmable matter
Jessica Smith,jessica.smith@example.com,Psionic technology
Nancy Anderson,nancy.anderson@example.com,Dimensional manipulation
David Robinson,david.robinson@example.com,Consciousness interfacing
Paul Harris,paul.harris@example.com,Xenoarchaeology
Linda Davis,linda.davis@example.com,Quantum computing
Mark Lewis,mark.lewis@example.com,Transwarp propulsion
Sarah Young,sarah.young@example.com,Terraforming
James Jackson,james.jackson@example.com,Xenolinguistics


Step 2: Create the Mongoose Script to Insert Documents

Create a file named `insertCrewMembers.js` with the following content:

```javascript
const mongoose = require('mongoose');
const fs = require('fs');
const readline = require('readline');

// MongoDB Cloud URI
const uri = "mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/mydatabase?retryWrites=true&w=majority&appName=Cluster0";

// Connect to MongoDB
mongoose.connect(uri).then(() => {
console.log('Connected to MongoDB Cloud');
insertCrewMembers();
}).catch((err) => {
console.error('Connection error', err);
});

// Define CrewMember Schema
const crewMemberSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
specialty: String
}, { collection: 'crewMembers' });

const CrewMember = mongoose.model('CrewMember', crewMemberSchema);

// Function to insert crew members from the text file
const insertCrewMembers = async () => {
const fileStream = fs.createReadStream('crewMembers.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});

const crewMembers = [];

for await (const line of rl) {
const [name, email, specialty] = line.split(',');
// Generating a random age between 25 and 40 for the crew members
const age = Math.floor(Math.random() * (40 - 25 + 1)) + 25;
crewMembers.push({ name, email, age, specialty });
}

try {
const result = await CrewMember.insertMany(crewMembers);
console.log('Crew members inserted:', result);
} catch (err) {
console.error('Error inserting crew members:', err);
} finally {
// Close the database connection
mongoose.connection.close().then(() => {
console.log('Mongoose connection closed');
}).catch(err => {
console.error('Error closing connection:', err);
});
}
};
```

### Explanation

1. **Connect to MongoDB**: The script connects to your MongoDB Cloud instance using Mongoose.
2. **Define Schema and Model**: A `CrewMember` schema and model are defined, with an additional `specialty` field.
3. **Read and Parse File**: The `insertCrewMembers` function reads the `crewMembers.txt` file line by line, splits each line into name, email, and specialty, and assigns a random age between 25 and 40 to each crew member.
4. **Insert Documents**: The `insertMany` method is used to insert all crew member records into the MongoDB collection.
5. **Error Handling and Connection Closure**: Errors are caught and logged, and the MongoDB connection is closed after the operation.

### Running the Program

Ensure you have the `crewMembers.txt` file in the same directory as `insertCrewMembers.js`, and then run the script with:

```bash
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.