Share
Explore

s24 May 31 Session 5 Full Stack Web Development

In this session, participants learn about NoSQL databases, specifically MongoDB, which uses JSON document storage.
You explore how to set up a MongoDB Atlas cluster, integrate it into a Node.js application using Mongoose, and perform CRUD operations.
Additionally, they benefit frp, using MongoDB Atlas for web and mobile applications, such as scalability, flexibility, and developer productivity. Practical exercises included creating a pet walking service datastore, managing data with Node.js scripts, and building the Pawsitive Care website.
This full-stack web development tutorial covered setting up an Express server, defining Mongoose models, and creating EJS views for a CRUD interface, all connected to a MongoDB Atlas database.
The session aimed to provide a comprehensive understanding of using JSON databases with MongoDB Atlas in modern application development.

Today’s Learning Outcomes:

The completed version of the Pawsitive Care website:


Class Plan:

Part 1 Understand what a MONGO db is : A database product : Free, paid service level
What kind of data storage mechanism does MONGO DB use? JSON document.
JSON : JavaScript Object Notation — This is the data structure for MONGO DB
Part 2: Getting hooked up to MONGODB in the cloud.
Part 3: MONGOOSE Lab: Building the Pet Store
Part 4: Doing CRUD with MONGOOSE APIs.
1
Data Persistence
Intro to NoSQL databases (Documents and collections)
Signing up for Mongo Atlas
Adding Mongo Atlas to an Express project
Installing Mongoose
Adding the Mongo Connection String
Creating a Model
Creating a Schema
Creating an Express GET endpoint that performs a query (.find, .findById)
MongoDB Documentation:
There are no rows in this table
“Why is it called a NOSql Database?”
Learning to use a Database Product called MONGO.
image.png

The data encoding format in MONGO is JSON: JavaScript Object Notation

JSON is a data description language (Just like HTML is a Page Description Language)
With JSON: You can change the shape of the data container dynamically under program control at runtime.
In NODE, we will be using the packages of to manage our Mongo Data Structures.
{
key:value,
key2:value2,
key3:{ keyx:valuex, keyy, valuey}
}
In JSON we have collections of { key: value, key2, value2 }
For a SQL database, the database structure is a very complex data structure created and maintained by the database Server.
Building the backend data persistance store for the 3 tier Model View Controller Web Application.
Understanding the SQL Data Store and how it differs from SQL.


megaphone

Advantages of a Network-Aware Distributed Database like JSON on MongoDB Atlas over a Local SQL Database for Web and Mobile Android Applications

As we continue to develop our web and mobile applications, it’s essential to choose the right database technology. While traditional local SQL databases have their merits, a network-aware distributed database like MongoDB Atlas, which uses JSON as its data format, offers significant advantages for modern web and mobile applications. Let's explore these benefits:

1. Scalability and Performance

Horizontal Scalability: MongoDB Atlas supports horizontal scaling through sharding, which means you can distribute data across multiple servers. This allows your application to handle increased loads and growing data volumes without performance degradation.
Optimized for Read/Write Operations: JSON’s flexible schema reduces the need for complex joins, often resulting in faster read and write operations. This is particularly beneficial for applications that require real-time data processing and quick access to large datasets.

2. Global Distribution and High Availability

Multi-Region Deployment: MongoDB Atlas allows you to deploy your database across multiple cloud regions, bringing data closer to your users. This reduces latency and enhances the user experience for global applications.
Automatic Failover: MongoDB Atlas provides built-in high availability with automatic failover. In the event of a node failure, the system automatically switches to a replica, ensuring continuous availability of your application.

3. Flexibility and Schema Evolution

Dynamic Schemas: JSON documents can easily accommodate changes in data structure without requiring a predefined schema. This flexibility is ideal for agile development environments where application requirements frequently change.
Easier Data Modeling: With JSON, you can represent complex hierarchical relationships and nested data structures naturally, aligning well with the needs of web and mobile applications.

4. Developer Productivity

JavaScript and Node.js Integration: MongoDB’s JSON format aligns seamlessly with JavaScript, making it easier for developers to work within a single language ecosystem. This reduces the learning curve and improves developer productivity.
Rich Query Language: MongoDB provides a powerful query language that supports rich queries, aggregations, and geospatial searches, which are critical for developing advanced features in web and mobile applications.

5. Managed Services and Operational Ease

Fully Managed Service: MongoDB Atlas handles database administration tasks such as backups, patch management, and monitoring, allowing developers to focus on application development rather than infrastructure management.
Automated Scaling and Updates: Atlas offers automated scaling and seamless updates, ensuring your database infrastructure can grow with your application without manual intervention.

6. Security and Compliance

Advanced Security Features: MongoDB Atlas includes features like end-to-end encryption, role-based access control, and IP whitelisting, ensuring that your data is secure both at rest and in transit.
Compliance Certifications: Atlas complies with various industry standards and regulations (e.g., GDPR, HIPAA), making it suitable for applications that handle sensitive user data.

7. Mobile Sync and Offline Access

Realm Mobile Database: MongoDB offers Realm, a mobile database that synchronizes with MongoDB Atlas. This provides real-time data sync and offline access, essential for mobile applications where connectivity may be intermittent.
Conflict Resolution: Built-in conflict resolution mechanisms ensure data integrity and consistency, even when multiple users are interacting with the same data simultaneously.

Practical Application in Web and Mobile Development

For web applications, the advantages of using MongoDB Atlas translate to better performance, easier scalability, and a more flexible development process.
For mobile Android applications, features like real-time sync with Realm ensure a seamless and responsive user experience, even in scenarios with poor or no internet connectivity.
By leveraging MongoDB Atlas, we can build robust, scalable, and high-performance web and mobile applications that meet the demands of modern users. The flexibility of JSON, combined with the distributed nature of MongoDB Atlas, positions us to create innovative solutions that can grow and adapt with our applications.
Let's harness these advantages as we integrate MongoDB Atlas into our development stack, ensuring we build scalable, reliable, and high-performing applications for our users.

Introduction to Using JSON Database Technology with MongoDB Atlas

Welcome to today's session on Full Stack Web Development!
In this class, we will be diving into the world of NoSQL databases with a focus on MongoDB Atlas, a powerful cloud-based solution for managing and scaling our data needs.
As we continue to build our three-tier Model View Controller (MVC) web application, understanding the advantages of JSON as a data model and how to leverage MongoDB Atlas will be crucial for our backend development.

Why “No SQL?’

What is the basis of a SQL database.
Codd’s 13 Laws: Basis of creating a database application to model a business domain:
Identify all the entities in the Business Domain.
Create Tables corresponding to the entities in the Business Domain.
For each table: you identify the attributes of that entity and you create them as fields in the Table.
Normalization to organize the tables: The basis of Normalization is the PRIMARY KEY
PROBLEM: WHAT HAPPENS WHEN YOU DON’T HAVE A PRIMARY KEY???
Big data is what happens when you don’t have a primary key!

Why Choose JSON and NoSQL over SQL?
Traditional SQL databases use structured tables and schemas to store data, which works well for many applications but can be limiting when dealing with more complex and variable data structures.

Here’s why JSON and NoSQL databases like MongoDB are becoming increasingly popular:
1. **Flexibility**:
JSON (JavaScript Object Notation) allows for a more flexible and dynamic schema design. You can easily store complex data structures and nested documents, which is perfect for modern web applications that need to adapt quickly to changing requirements.
2. **Scalability**:
NoSQL databases are designed to scale out horizontally, making it easier to handle large volumes of traffic and data. MongoDB Atlas, in particular, provides automatic sharding and scaling, ensuring your application remains performant as it grows.
3. **Speed**:
JSON data models can lead to faster read and write operations. MongoDB’s document-oriented approach reduces the need for complex joins and can improve performance for many types of queries.
4. **Developer Productivity**:
Working with JSON feels natural in JavaScript and Node.js environments, reducing the cognitive load on developers and accelerating development cycles.

Getting Started with MongoDB Atlas

MongoDB Atlas is a fully-managed cloud database service that takes care of the infrastructure, security, and backups, allowing us to focus on building our application.
Here's how we'll integrate MongoDB Atlas into our Node.js project:
1. **Signing Up for MongoDB Atlas**:
- Visit the [MongoDB Atlas website](https://www.mongodb.com/cloud/atlas) and create an account.

- Follow the guided setup to create your first cluster.

image.png

image.png

Setting Up a Simple, Cost-Free MongoDB Atlas Cluster for Today's Lab

For today's lab, we'll focus on setting up a free, simple MongoDB Atlas cluster that's easy for students to use for our proof of concept.
We'll go through the steps to create a "Shared" cluster, which is free and sufficient for our learning purposes.

Step-by-Step Guide to Creating a Free MongoDB Atlas Cluster

Sign Up for MongoDB Atlas:
Visit the and sign up for a free account.
Create a New Cluster:
Once logged in, navigate to the Clusters section in the Atlas dashboard.
Click on Create New Cluster.
Select the Free Tier:
Choose the Shared option, which includes the M0 free tier.
Configure the Cluster:
Cloud Provider & Region: Select any region that offers the free tier. Popular options include AWS (N. Virginia) or Google Cloud (Oregon).
Cluster Tier: Ensure you select the M0 (Free Tier). This option offers 512 MB of storage, which is sufficient for our initial experiments.
Cluster Name:
Give your cluster a name, such as MyFirstCluster.
Create Cluster:
Click on Create Cluster. The setup process may take a few minutes.

Connecting to Your MongoDB Atlas Cluster

Once your cluster is created, follow these steps to connect it to your Node.js application:
Whitelist Your IP Address:
Go to the Network Access section in the Atlas dashboard.
Click Add IP Address and select Allow Access from Anywhere for convenience during the lab. You can refine this later for better security.
Get Your Connection String:
Go to the Clusters section and click on Connect for your newly created cluster.
Choose Connect Your Application.
Copy the provided connection string. It will look something like this:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority
Replace <username>, <password>, and <dbname> with your actual MongoDB Atlas username, password, and database name.
Install Mongoose:
In your Node.js project, install Mongoose by running:
npm install mongoose
Connect to MongoDB Atlas:
Use the following code to connect your application to MongoDB Atlas:
const mongoose = require('mongoose');

mongoose.connect('your_connection_string', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err));

Summary

By following these steps, you'll have a free, easy-to-use MongoDB Atlas cluster set up for today's lab. This setup is perfect for getting started and allows you to focus on learning without worrying about costs or complex configurations. Let's get started with creating our cluster and connecting it to our Node.js application!

**Setting Up MongoDB Atlas in Your Node.js Application**:
- **Install Mongoose**: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js, providing a straightforward way to model your data. Install it using npm: ```bash npm install mongoose
**Add the MongoDB Connection String**:
In your Atlas dashboard, obtain your connection string and add it to your Node.js application.
Typically, this is done in a configuration file or directly in your app’s initialization code.

image.png


Now you are setup with the connection credentials to access MongoDB Atlas:

Next steps:

Integrate MongoDB Atlas with Node.js
Lab: Installing Mongoose, adding the connection string, and setting up your first schema and model.
Create an Express GET Endpoint**:
Develop a GET endpoint that performs queries using `.find` and `.findById` methods, allowing you to retrieve data from your MongoDB Atlas database.

Creating and Querying Data**:

- Create schemas and models to represent your data. - Perform CRUD operations (Create, Read, Update, Delete) to interact with your database.

- **Create a Model and Schema**:
Define your data structure using Mongoose schemas and models, which will help in validating and organizing your data.

Connecting to MongoDB Atlas

- Use Mongoose to connect to your MongoDB Atlas cluster.
Here’s a basic example: ```javascript const mongoose = require('mongoose');
mongoose.connect('your_connection_string', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected...')) .catch(err => console.log(err));

info

The elements of a MONGO data store:

Introduction to JSON Databases Using a Pet Walking Service Example

Welcome and Overview

Welcome, everyone! Today, we're going to dive into the theory behind JSON databases, using our pet walking service as an example. We'll explore how MongoDB, a popular JSON database, stores data and collections, and why JSON is such a powerful format for modern web applications.

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that's easy for humans to read and write and easy for machines to parse and generate. JSON is used primarily to transmit data between a server and a web application as text.
Example of a JSON object:
json
Copy code
{
"name": "Buddy",
"type": "Dog",
"breed": "Golden Retriever",
"age": 3,
"ownerID": "client1"
}

Why JSON?

Native to JavaScript: JSON is based on a subset of JavaScript, which means it works natively with JavaScript environments. This makes it ideal for use with Node.js and other JavaScript frameworks.
Human-Readable: JSON is easy to read and write for developers, making debugging and data manipulation straightforward.
Interoperability: JSON is language-agnostic, meaning it can be used across different programming languages, making it an excellent choice for web APIs and data interchange.

How MongoDB Uses JSON

MongoDB is a NoSQL database that uses a document-oriented data model. Here's how it works:
Database: The highest level of organization in MongoDB, analogous to a database in a SQL system.
Collections: Collections are analogous to tables in SQL. They group related documents together.
Documents: The basic unit of data in MongoDB, similar to a row in a SQL table, but more flexible. Documents are JSON-like objects, stored in a binary format called BSON (Binary JSON).

Data Model for Pet Walking Service

Let's use our pet walking service to illustrate how MongoDB stores data. We'll have three collections: Pets, DogWalkers, and Clients.
Pets Collection:
json
Copy code
{
"name": "Buddy",
"type": "Dog",
"breed": "Golden Retriever",
"age": 3,
"ownerID": "client1"
}

DogWalkers Collection:
json
Copy code
{
"name": "Alice",
"rating": 4.9,
"available": true
}

Clients Collection:
json
Copy code
{
"name": "John Doe",
"contact": "john@example.com"
}

How MongoDB Stores Data

Dynamic Schemas: Unlike SQL databases, MongoDB does not require a predefined schema. This means each document in a collection can have a different structure.
Embedded Documents: MongoDB allows for embedded documents and arrays, enabling complex data hierarchies within a single document.
Indexing: MongoDB supports indexing to optimize query performance. You can create indexes on fields within your documents, similar to SQL indexes.

Advantages of Using MongoDB for Our Pet Walking Service

Flexibility: The dynamic schema nature of MongoDB allows us to easily evolve our data model as the application requirements change without needing to modify a rigid schema.
Scalability: MongoDB can handle large amounts of data and high traffic loads by scaling horizontally. This is crucial for applications expected to grow over time.
Speed: JSON documents can be accessed and manipulated quickly, making read and write operations fast, which is essential for real-time applications.

Practical Example: Connecting Node.js to MongoDB

Here's a practical example of how to connect our Node.js application to MongoDB and create our collections.
Install MongoDB Driver:
bash
Copy code
npm install mongodb

Connect to MongoDB:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";

const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});

async function run() {
try {
await client.connect();
console.log("Connected to MongoDB!");

const database = client.db('PetWalkingService');
const pets = database.collection('Pets');
const dogWalkers = database.collection('DogWalkers');
const clients = database.collection('Clients');

const petData = [
{ name: 'Buddy', type: 'Dog', breed: 'Golden Retriever', age: 3, ownerID: 'client1' },
{ name: 'Mittens', type: 'Cat', breed: 'Tabby', age: 5, ownerID: 'client2' }
];

const dogWalkerData = [
{ name: 'Alice', rating: 4.9, available: true },
{ name: 'Bob', rating: 4.7, available: false }
];

const clientData = [
{ name: 'John Doe', contact: 'john@example.com' },
{ name: 'Jane Smith', contact: 'jane@example.com' }
];

await pets.insertMany(petData);
await dogWalkers.insertMany(dogWalkerData);
await clients.insertMany(clientData);

console.log("Data inserted successfully!");

} finally {
await client.close();
}
}

run().catch(console.dir);

Conclusion

By using MongoDB and JSON, we can build flexible, scalable, and high-performance data models that are perfect for modern web and mobile applications. The example of our pet walking service illustrates how easy it is to model complex data structures and interact with them using Node.js.
In today's lab, you'll set up your own MongoDB Atlas cluster, connect it to your Node.js application, and create collections for pets, dog walkers, and clients. Let's get started!
ChatGPT can make mistakes. Check important info.
megaphone

Lab: Building a Pet Walking Service Datastore with MongoDB and Node.js


In this lab, we will create a MongoDB database using Node.js to model a datastore for a pet walking service. This service will include information about pets, dog walkers, and clients. We'll be using MongoDB Atlas for our database, leveraging the provided connection string to integrate it into our application.
#### Prerequisites - Ensure Node.js and npm are installed on your machine. - Have access to MongoDB Atlas with the provided credentials.
#### Step 1: Set Up Your Node.js Project
1. **Initialize a new Node.js project**: ```bash mkdir pet-walking-service cd pet-walking-service npm init -y ```
2. **Install MongoDB driver**: ```bash npm install mongodb ```
#### Step 2: Connect to MongoDB Atlas
Create a file named `index.js` and add the following code to connect to MongoDB Atlas:
```javascript const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } });
async function run() { try { // Connect the client to the server (optional starting in v4.7) await client.connect(); // Send a ping to confirm a successful connection await client.db("admin").command({ ping: 1 }); console.log("Pinged your deployment. You successfully connected to MongoDB!");
// Define the database and collections const database = client.db('PetWalkingService'); const pets = database.collection('Pets'); const dogWalkers = database.collection('DogWalkers'); const clients = database.collection('Clients');
// Sample data const petData = [ { name: 'Buddy', type: 'Dog', breed: 'Golden Retriever', age: 3, ownerID: 'client1' }, { name: 'Mittens', type: 'Cat', breed: 'Tabby', age: 5, ownerID: 'client2' } ];
const dogWalkerData = [ { name: 'Alice', rating: 4.9, available: true }, { name: 'Bob', rating: 4.7, available: false } ];
const clientData = [ { name: 'John Doe', contact: 'john@example.com' }, { name: 'Jane Smith', contact: 'jane@example.com' } ];
// Insert data into collections await pets.insertMany(petData); await dogWalkers.insertMany(dogWalkerData); await clients.insertMany(clientData);
console.log("Sample data inserted successfully!");
} finally { // Ensures that the client will close when you finish/error await client.close(); } }
run().catch(console.dir); ```
#### Step 3: Run the Application
1. **Run the script**: ```bash node index.js ```
2. **Verify the output**: - You should see messages confirming the connection to MongoDB and the insertion of sample data.
#### Explanation of the Code
- **Connection Setup**: The code initializes a connection to MongoDB Atlas using the provided connection string. - **Database and Collections**: It defines a new database named `PetWalkingService` and creates three collections: `Pets`, `DogWalkers`, and `Clients`. - **Sample Data Insertion**: The code inserts sample documents into each collection to simulate the data of a pet walking service. - **Cleanup**: The connection to the database is closed once the operations are complete.
#### Summary
In this lab, you've learned how to set up a MongoDB Atlas database, connect to it using Node.js, and create collections for a pet walking service. You inserted sample data into the collections, providing a solid foundation for building out the application further.
Feel free to expand on this example by adding more features, such as querying the data, updating records, or integrating it with an Express.js server to create a full-fledged backend for your application.

megaphone

Step 2 : read the data back out

### Reading Records from MongoDB using Node.js
Now that we have successfully inserted records into our MongoDB database, let's write a Node.js program to read and display these records.
This program will connect to the MongoDB Atlas cluster, query the collections, and print the results.
#### Step-by-Step Guide
1. **Create a new file named `readRecords.js`** in your project directory.
2. **Add the following code** to `readRecords.js`:
```javascript const { MongoClient, ServerApiVersion } = require('mongodb'); const uri = "mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } });
async function readRecords() { try { // Connect the client to the server await client.connect(); console.log("Connected to MongoDB!");
const database = client.db('PetWalkingService');
// Define the collections const petsCollection = database.collection('Pets'); const dogWalkersCollection = database.collection('DogWalkers'); const clientsCollection = database.collection('Clients');
// Fetch all documents from each collection const pets = await petsCollection.find({}).toArray(); const dogWalkers = await dogWalkersCollection.find({}).toArray(); const clients = await clientsCollection.find({}).toArray();
// Print the fetched documents console.log("Pets:"); console.log(pets);
console.log("\nDog Walkers:"); console.log(dogWalkers);
console.log("\nClients:"); console.log(clients);
} catch (err) { console.error("Error reading records:", err); } finally { // Ensures that the client will close when you finish/error await client.close(); } }
readRecords().catch(console.dir); ```
#### Explanation of the Code
- **Connection Setup**: We use the same connection string to connect to the MongoDB Atlas cluster. - **Database and Collections**: We specify the database (`PetWalkingService`) and the collections (`Pets`, `DogWalkers`, `Clients`). - **Fetching Documents**: We use the `.find({})` method to fetch all documents from each collection and convert them to an array with `.toArray()`. - **Printing Documents**: We print the fetched documents to the console.
#### Running the Program
1. **Run the script**: ```bash node readRecords.js ```
2. **Verify the output**: - You should see the documents from the `Pets`, `DogWalkers`, and `Clients` collections printed to the console.
### Conclusion
By following this guide, you have successfully written a Node.js program to read and display records from your MongoDB Atlas database. This is a crucial step in understanding how to interact with your data, enabling you to build more complex queries and functionality for your web or mobile application.
Feel free to expand this script by adding more complex queries, filtering, or even integrating it with an Express.js server to create a full-featured API.

megaphone

Let’s finish the CRUD set of operations


### Update and Delete Operations in MongoDB using Node.js
Now that we have successfully read records from our MongoDB database, let's write some Node.js scripts to perform update and delete operations on the data.
#### Step-by-Step Guide
1. **Create a new file named `updateRecords.js`** in your project directory.
2. **Add the following code** to `updateRecords.js` to update records:
```javascript const { MongoClient, ServerApiVersion } = require('mongodb'); const uri = "mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } });
async function updateRecords() { try { await client.connect(); console.log("Connected to MongoDB!");
const database = client.db('PetWalkingService');
// Update a specific pet's age const petsCollection = database.collection('Pets'); const updateResult = await petsCollection.updateOne( { name: 'Buddy' }, // Filter criteria { $set: { age: 4 } } // Update operation ); console.log(`${updateResult.matchedCount} document(s) matched the filter, updated ${updateResult.modifiedCount} document(s)`);
// Update multiple dog walkers to set them as available const dogWalkersCollection = database.collection('DogWalkers'); const updateManyResult = await dogWalkersCollection.updateMany( { available: false }, // Filter criteria { $set: { available: true } } // Update operation ); console.log(`${updateManyResult.matchedCount} document(s) matched the filter, updated ${updateManyResult.modifiedCount} document(s)`);
} catch (err) { console.error("Error updating records:", err); } finally { await client.close(); } }
updateRecords().catch(console.dir); ```
3. **Run the update script**: ```bash node updateRecords.js ```

4. **Create a new file named `deleteRecords.js`** in your project directory.

5. **Add the following code** to `deleteRecords.js` to delete records:
```javascript const { MongoClient, ServerApiVersion } = require('mongodb'); const uri = "mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } });
async function deleteRecords() { try { await client.connect(); console.log("Connected to MongoDB!");
const database = client.db('PetWalkingService');
// Delete a specific pet by name const petsCollection = database.collection('Pets'); const deleteResult = await petsCollection.deleteOne({ name: 'Buddy' }); console.log(`Deleted ${deleteResult.deletedCount} document(s)`);
// Delete all clients with a specific contact email const clientsCollection = database.collection('Clients'); const deleteManyResult = await clientsCollection.deleteMany({ contact: 'john@example.com' }); console.log(`Deleted ${deleteManyResult.deletedCount} document(s)`);
} catch (err) { console.error("Error deleting records:", err); } finally { await client.close(); } }
deleteRecords().catch(console.dir); ```
6. **Run the delete script**: ```bash node deleteRecords.js ```
### Explanation of the Code
#### Update Operations (`updateRecords.js`)
- **Update One Document**: ```javascript const updateResult = await petsCollection.updateOne( { name: 'Buddy' }, // Filter criteria { $set: { age: 4 } } // Update operation ); ``` This updates the `age` of the pet named "Buddy" to 4.
- **Update Multiple Documents**: ```javascript const updateManyResult = await dogWalkersCollection.updateMany( { available: false }, // Filter criteria { $set: { available: true } } // Update operation ); ``` This sets the `available` status to `true` for all dog walkers who are currently `available: false`.
#### Delete Operations (`deleteRecords.js`)
- **Delete One Document**: ```javascript const deleteResult = await petsCollection.deleteOne({ name: 'Buddy' }); ``` This deletes the pet named "Buddy".
- **Delete Multiple Documents**: ```javascript const deleteManyResult = await clientsCollection.deleteMany({ contact: 'john@example.com' }); ``` This deletes all clients with the contact email "john@example.com".
### Conclusion
By following these examples, you now have scripts to perform update and delete operations on your MongoDB database using Node.js. These operations are fundamental for maintaining and manipulating data in your applications. Feel free to expand these scripts by adding more complex queries and operations to suit your application's needs. Happy coding!


minus

Building the Pawsitive Care Website


Building a Complete IT Application for Pet Walking Service with MongoDB, Node.js, and Express

In this tutorial, we will build a full-fledged CRUD (Create, Read, Update, Delete) application for our pet walking service.
We will front-end our MongoDB database with an Express web server and use HTML forms to perform CRUD operations.

Step-by-Step Guide

1. **Set Up Your Project**: - Initialize a new Node.js project: ```bash mkdir pet-walking-service-app cd pet-walking-service-app npm init -y ``` - Install required dependencies: ```bash npm install express body-parser mongoose ejs : DONE ```
2. **Project Structure**: Create the following directory and file structure: ``` pet-walking-service-app ├── views │ ├── index.ejs │ ├── pets.ejs │ ├── add-pet.ejs │ ├── update-pet.ejs │ ├── dogwalkers.ejs │ └── clients.ejs ├── models │ ├── Pet.js │ ├── DogWalker.js │ └── Client.js ├── public │ └── styles.css ├── index.js └── package.json ```
3. **Define Mongoose Models**: - **models/Pet.js**: done ```javascript const mongoose = require('mongoose');
const petSchema = new mongoose.Schema({ name: String, type: String, breed: String, age: Number, ownerID: String });
module.exports = mongoose.model('Pet', petSchema); ```
- **models/DogWalker.js**: done ```javascript const mongoose = require('mongoose');
const dogWalkerSchema = new mongoose.Schema({ name: String, rating: Number, available: Boolean });
module.exports = mongoose.model('DogWalker', dogWalkerSchema); ```
- **models/Client.js**: done ```javascript const mongoose = require('mongoose');
const clientSchema = new mongoose.Schema({ name: String, contact: String });
module.exports = mongoose.model('Client', clientSchema); ```

4. **Create Express Server**:

- **index.js**: done ```javascript const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const Pet = require('./models/Pet'); const DogWalker = require('./models/DogWalker'); const Client = require('./models/Client');
const app = express();
// Connect to MongoDB mongoose.connect('mongodb+srv://petersigurdson:EdHurHzNyIJ5h4se@cluster0.vbtw6ws.mongodb.net/PetWalkingService?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true });
// Middleware app.use(bodyParser.urlencoded({ extended: true })); app.set('view engine', 'ejs'); app.use(express.static('public'));
// Routes app.get('/', (req, res) => { res.render('index'); });
// Pet CRUD operations app.get('/pets', async (req, res) => { const pets = await Pet.find(); res.render('pets', { pets }); });
app.get('/pets/add', (req, res) => { res.render('add-pet'); });
app.post('/pets/add', async (req, res) => { const pet = new Pet(req.body); await pet.save(); res.redirect('/pets'); });
app.get('/pets/update/:id', async (req, res) => { const pet = await Pet.findById(req.params.id); res.render('update-pet', { pet }); });
app.post('/pets/update/:id', async (req, res) => { await Pet.findByIdAndUpdate(req.params.id, req.body); res.redirect('/pets'); });
app.post('/pets/delete/:id', async (req, res) => { await Pet.findByIdAndDelete(req.params.id); res.redirect('/pets'); });
// Similar CRUD operations for DogWalkers and Clients...
// Start server const port = 3000; app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); }); ```

5. **Create Views**:

- **views/index.ejs**: done ```html <!DOCTYPE html> <html> <head> <title>Pet Walking Service</title> </head> <body> <h1>Welcome to the Pet Walking Service</h1> <a href="/pets">View Pets</a> <a href="/dogwalkers">View Dog Walkers</a> <a href="/clients">View Clients</a> </body> </html> ```
- **views/pets.ejs**: done ```html <!DOCTYPE html> <html> <head> <title>Pets</title> </head> <body> <h1>Pets</h1> <a href="/pets/add">Add Pet</a> <ul> <% pets.forEach(pet => { %> <li> <%= pet.name %> - <%= pet.type %> - <%= pet.breed %> - <%= pet.age %> years old <a href="/pets/update/<%= pet._id %>">Update</a> <form action="/pets/delete/<%= pet._id %>" method="POST" style="display:inline;"> <button type="submit">Delete</button> </form> </li> <% }) %> </ul> </body> </html> ```
- **views/add-pet.ejs**: done ```html <!DOCTYPE html> <html> <head> <title>Add Pet</title> </head> <body> <h1>Add Pet</h1> <form action="/pets/add" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <br> <label for="type">Type:</label> <input type="text" id="type" name="type" required> <br> <label for="breed">Breed:</label> <input type="text" id="breed" name="breed" required> <br> <label for="age">Age:</label> <input type="number" id="age" name="age" required> <br> <label for="ownerID">Owner ID:</label> <input type="text" id="ownerID" name="ownerID" required> <br> <button type="submit">Add Pet</button> </form> </body> </html> ```
- **views/update-pet.ejs**: done ```html <!DOCTYPE html> <html> <head> <title>Update Pet</title> </head> <body> <h1>Update Pet</h1> <form action="/pets/update/<%= pet._id %>" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= pet.name %>" required> <br> <label for="type">Type:</label> <input type="text" id="type" name="type" value="<%= pet.type %>" required> <br> <label for="breed">Breed:</label> <input type="text" id="breed" name="breed" value="<%= pet.breed %>" required> <br> <label for="age">Age:</label> <input type="number" id="age" name="age" value="<%= pet.age %>" required> <br> <label for="ownerID">Owner ID:</label> <input type="text" id="ownerID" name="ownerID" value="<%= pet.ownerID %>" required> <br> <button type="submit">Update Pet</button> </form> </body> </html> ```
6. **Add CSS Styles** (DONE): - **public/styles.css**: ```css body { font-family: Arial, sans-serif; margin: 20px; } ```
7. **Running the Application**: - Start the server: ```bash node index.js ``` - Open your web browser and go to `http://localhost:3000`.
8. **Extend CRUD Operations for DogWalkers and Clients**: - Repeat the steps for pets to create similar views and routes for dog walkers and clients.
Workflow Instructions for the setup
1. **Set up your project directory and initialize a Node.js project**. 2. **Install the required dependencies** using `npm install`. 3. **Create the Mongoose models** for your data. 4. **Set up the Express server** and
Connect to your MongoDB Atlas cluster. 5. **Create views using EJS** for displaying, adding, updating, and deleting data. 6. **Define routes in Express** to handle CRUD operations. 7. **Run your application** and verify the CRUD functionality through the web interface. 8. **Optionally, add CSS for styling** your application.
By following these steps, you'll have a complete IT application for managing a pet walking service, showcasing how to integrate MongoDB, Node.js, and Express for a full-stack web application.
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.