Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions Week3/assignment/exercise1-normalization.md

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very clear explanation! Good job!

Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Exercise 3.1 - SQL Normalization

Original table:

member_id | member_name | member_address | dinner_id | dinner_date | venue_code | venue_description | food_code | food_description
--------- | ----------- | -------------- | --------- | ----------- | ---------- | ----------------- | ---------- | ----------------
... | ... | ... | ... | ... | ... | ... | C1, C2 | Curry, Cake
... | ... | ... | ... | ... | ... | ... | P1, T1, M1 | Pie, Tea, Mousse
etc.

---

## 1. Which columns violate 1NF?

1NF (First Normal Form) requires:

- Each field contains **atomic** (indivisible) values.
- No repeating groups or lists in a single column.
- All values in a column are of the same type.

In this table, 1NF is violated by:

- **food_code** - contains multiple values separated by commas, e.g. `C1, C2`, `P1, T1, M1`.
- **food_description** - also contains multiple values separated by commas, e.g. `Curry, Cake`, `Pie, Tea, Mousse`.

Additionally, **dinner_date** is stored in multiple different formats (`2020-03-15`, `20-03-2020`, `Mar 25 '20`), which is bad practice, but they are still single scalar values. The main 1NF violation is the multi-valued food columns.

---

## 2. Which entities can be extracted?

From the table we can identify the following entities:

1. **Member**
- member_id
- member_name
- member_address

2. **Dinner (Event)**
- dinner_id
- dinner_date
- venue_code (the place where the dinner is held)

3. **Venue**
- venue_code
- venue_description

4. **Food**
- food_code
- food_description

5. **MemberDinner / Attendance**
- which member attended which dinner
(many-to-many relationship between Member and Dinner)

6. **DinnerFood / Menu**
- which food items were served at a given dinner
(many-to-many relationship between Dinner and Food)

---

## 3. Tables and columns for a 3NF-compliant solution

Below is a 3NF schema.

### 1. Table `members`

- **member_id** (PK)
- member_name
- member_address

Functional dependency:
`member_id → member_name, member_address`
No transitive dependencies.

---

### 2. Table `venues`

- **venue_code** (PK)
- venue_description

Functional dependency:
`venue_code → venue_description`

---

### 3. Table `dinners`

- **dinner_id** (PK)
- dinner_date (DATE type)
- venue_code (FK → venues.venue_code)

Functional dependency:
`dinner_id → dinner_date, venue_code`

---

### 4. Table `foods`

- **food_code** (PK)
- food_description

Functional dependency:
`food_code → food_description`

---

### 5. Table `member_dinners` (attendance)

- **member_id** (FK → members.member_id)
- **dinner_id** (FK → dinners.dinner_id)
- (PK is the combination (member_id, dinner_id))

This table represents which member attended which dinner (many-to-many).

---

### 6. Table `dinner_foods` (menu per dinner)

- **dinner_id** (FK → dinners.dinner_id)
- **food_code** (FK → foods.food_code)
- (PK is the combination (dinner_id, food_code))

This table replaces the multi-valued fields `food_code` and `food_description` by storing one row per dinner–food combination.

---

## Final 3NF schema

- `members(member_id PK, member_name, member_address)`
- `venues(venue_code PK, venue_description)`
- `dinners(dinner_id PK, dinner_date, venue_code FK)`
- `foods(food_code PK, food_description)`
- `member_dinners(member_id FK, dinner_id FK, PK(member_id, dinner_id))`
- `dinner_foods(dinner_id FK, food_code FK, PK(dinner_id, food_code))`
71 changes: 71 additions & 0 deletions Week3/assignment/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
require("dotenv").config()
const { MongoClient, ObjectId } = require("mongodb")

const uri = process.env.MONGODB_URI

if (!uri) {
throw new Error("Please set MONGODB_URI in your .env file")
}

async function main() {
const client = new MongoClient(uri)

try {
await client.connect()
console.log("Connected to MongoDB Atlas")

const db = client.db("databaseWeek3")
const episodes = db.collection("bob_ross_episodes")

const newEpisode = {
title: "My Custom Joy of Painting Episode",
season: 100,
episode: 1,
elements: ["happy little trees", "mountain", "lake"],
aired_on: new Date("2025-01-01"),
}

const insertResult = await episodes.insertOne(newEpisode)
console.log("Inserted new episode with _id:", insertResult.insertedId)


const insertedId = insertResult.insertedId
const foundById = await episodes.findOne({ _id: insertedId })

const cursor = episodes.find({ elements: "happy little trees" })
const episodesWithTrees = await cursor.toArray()

console.log(
`Episodes with "happy little trees": ${episodesWithTrees.length}`
)

const updateResult = await episodes.updateOne(
{ _id: insertedId },
{
$set: {
title: "Updated Custom Joy of Painting Episode",
updated_at: new Date(),
},
}
)

console.log(
`Updated episodes: matched ${updateResult.matchedCount}, modified ${updateResult.modifiedCount}`
)

const updatedDoc = await episodes.findOne({ _id: insertedId })

const deleteResult = await episodes.deleteOne({ _id: insertedId })
console.log(`Deleted documents: ${deleteResult.deletedCount}`)
} catch (err) {
console.error("MongoDB error:", err)
} finally {
await client.close()
console.log("Connection to MongoDB closed")
}
}

main().catch((err) => {
console.error(err)
process.exit(1)
})
Loading