s24 Lesson Plan Full Stack Web Development TUE JUNE 4

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:


Lab Topics:

Creating a MODEL
Creating a SCHEMA
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: '',
age: 30

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


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);


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: '' });

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

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


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);


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.


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!

United Earth Space Force

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,,Astrobiology
Jane Smith,,Exobiology
James Brown,,Xenobiology
Mary Johnson,,Astrochemistry
Robert Jones,,Molecular engineering
Linda Davis,,Metamaterials
Michael Wilson,,Programmable matter
Sarah Miller,,Psionic technology
David Martinez,,Dimensional manipulation
Laura Garcia,,Consciousness interfacing
Kevin Anderson,,Xenoarchaeology
Karen Thomas,,Quantum computing
Matthew Jackson,,Transwarp propulsion
Patricia White,,Terraforming
Daniel Harris,,Xenolinguistics
Barbara Clark,,Astrobiology
Paul Lewis,,Exobiology
Nancy Robinson,,Xenobiology
Mark Walker,,Astrochemistry
Sandra Young,,Molecular engineering
John Smith,,Metamaterials
Lisa Johnson,,Programmable matter
James White,,Psionic technology
Michael Brown,,Dimensional manipulation
Emily Davis,,Consciousness interfacing
David Wilson,,Xenoarchaeology
Sarah Martinez,,Quantum computing
Jessica Lee,,Transwarp propulsion
Daniel Anderson,,Terraforming
Laura Thomas,,Xenolinguistics
Nancy Jackson,,Astrobiology
Paul Walker,,Exobiology
Karen Lewis,,Xenobiology
Sandra Harris,,Astrochemistry
Emily Clark,,Molecular engineering
James Robinson,,Metamaterials
Michael Young,,Programmable matter
Linda Jackson,,Psionic technology
Barbara Lee,,Dimensional manipulation
Mark Davis,,Consciousness interfacing
Kevin Martinez,,Xenoarchaeology
Lisa Brown,,Quantum computing
Patricia White,,Transwarp propulsion
John Harris,,Terraforming
David Clark,,Xenolinguistics
James Walker,,Astrobiology
Michael Martinez,,Exobiology
Nancy Davis,,Xenobiology
Linda Lee,,Astrochemistry
Paul Brown,,Molecular engineering
Barbara Wilson,,Metamaterials
David Johnson,,Programmable matter
Sarah Smith,,Psionic technology
Jessica Harris,,Dimensional manipulation
Daniel Clark,,Consciousness interfacing
John Lewis,,Xenoarchaeology
Kevin White,,Quantum computing
Laura Robinson,,Transwarp propulsion
Michael Anderson,,Terraforming
Nancy Martinez,,Xenolinguistics
James Harris,,Astrobiology
Sandra Johnson,,Exobiology
David Lee,,Xenobiology
Karen Walker,,Astrochemistry
Paul Young,,Molecular engineering
Barbara Martinez,,Metamaterials
Kevin Jackson,,Programmable matter
Sarah Robinson,,Psionic technology
James Brown,,Dimensional manipulation
Linda Harris,,Consciousness interfacing
Mark Clark,,Xenoarchaeology
Nancy Smith,,Quantum computing
John Davis,,Transwarp propulsion
Jessica Martinez,,Terraforming
Kevin Johnson,,Xenolinguistics
David White,,Astrobiology
Emily Brown,,Exobiology
Paul Martinez,,Xenobiology
Sandra Lee,,Astrochemistry
Michael Jackson,,Molecular engineering
Linda White,,Metamaterials
Barbara Johnson,,Programmable matter
Jessica Smith,,Psionic technology
Nancy Anderson,,Dimensional manipulation
David Robinson,,Consciousness interfacing
Paul Harris,,Xenoarchaeology
Linda Davis,,Quantum computing
Mark Lewis,,Transwarp propulsion
Sarah Young,,Terraforming
James Jackson,,Xenolinguistics

Step 2: Create the Mongoose Script to Insert Documents

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

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

// MongoDB Cloud URI
const uri = "mongodb+srv://";

// Connect to MongoDB
mongoose.connect(uri).then(() => {
console.log('Connected to MongoDB Cloud');
}).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:

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.