Share
Explore

Node.js Fullstack Application Template

Below is a simple Lab Workbook that can guide students in setting up MongoDB with Mongoose and creating 10 sample data records for a men's wear eCommerce website.

testconnectiontomongo.js
megaphone

const mongoose = require('mongoose');


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

// Product Schema
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true, min: 0 },
category: { type: String, required: true },
inStock: { type: Boolean, default: true }
});

// Creating and Exporting the Model
const Product = mongoose.model('Product', productSchema);
module.exports = Product;

done: LAB WORKBOOK 1: Setting Up MongoDB with Mongoose
=============================================

Introduction
------------
In this lab, we will set up MongoDB with Mongoose and create 10 sample data records for a men's wear eCommerce website. We will cover the installation process, database connection, schema creation, and data insertion.

Step 1: Installing MongoDB
--------------------------
Please follow the official guide to install MongoDB on your system:
https://docs.mongodb.com/manual/installation/

Step 2: Installing Mongoose
---------------------------
Create a new directory for your project and navigate into it. Then run the following command to initialize a Node.js project and install Mongoose:


$ npm init
$ npm install mongoose
Step 3: Connecting to MongoDB using Mongoose and creating a Schema
--------------------------------------------
Create a file called `model.js` This is the mediator between your Application and MongoDB:

const mongoose = require('mongoose');

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

// Product Schema
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true, min: 0 },
category: { type: String, required: true },
inStock: { type: Boolean, default: true }
});
//Creating the MODEL
const Product = mongoose.model('Product', productSchema);

// Exporting the Model
module.exports = Product;
p 4: Creating a Product Schema

Step 5: Generate Starter Data:

Add the following code to create and insert 10 sample product records into the database:

// generateStarterData.js
const mongoose = require('mongoose');
const Product = require('./model'); // Importing the Product model

mongoose.connect('mongodb://127.0.0.1:27017/mensWearDB', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to MongoDB');
// Use the Product model here
const product = new Product({
name: 'Shirt',
price: 29.99,
category: 'Tops',
inStock: true
});

product.save().then(() => {
console.log('Product saved');
mongoose.connection.close();
});
})
.catch(err => console.error('Connection error', err));


Working code to insert data:
megaphone

const mongoose = require('mongoose');


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

// Product Schema
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true, min: 0 },
category: { type: String, required: true },
inStock: { type: Boolean, default: true }
});

// Creating the MODEL
const Product = mongoose.model('Product', productSchema);

// Use the Product model here
const product = new Product({
name: 'Shirt',
price: 29.99,
category: 'Tops',
inStock: true
});

product.save().then(() => {
console.log('Product saved');
mongoose.connection.close();
});

// Exporting the Model
module.exports = Product;

Now, the code first connects to the MongoDB instance, then it defines a schema and model for a product, creates an instance of a product, saves it, and exports the product model.

Step 6: Running the Code

Run the following command to execute the code:

$ node app.js

You should see a message indicating a successful connection to MongoDB and confirmation that the data has been added.

Conclusion

Congratulations! You have successfully set up MongoDB with Mongoose and created 10 sample data records for a men's wear eCommerce website. You can now build upon this foundation to create more complex applications and explore additional features of MongoDB and Mongoose.
cssCopy code

This workbook provides a simple and clear guide to setting up MongoDB with Mongoose, suitable for beginners. Feel free to customize the content to align with your teaching objectives and the needs of your students.


Part 2


Below is the extended workbook that now includes steps to create a front-end web page with HTML and CSS to perform CRUD (Create, Read, Update, Delete) operations, using microservices and AJAX. It connects to the database you've created earlier.
LAB WORKBOOK Part 2: Building a Front-End for MongoDB CRUD Operations
========================================================================

Introduction
------------
Building on our previous lab, we will now create a front-end using HTML and CSS with forms to add records and retrieve and display records from our men's wear eCommerce website. We will perform CRUD operations using microservices and AJAX.

Step 7: Setting Up the Backend (Node.js + Express)
--------------------------------------------------

Create a new file `server.js`, and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const app = express();
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(cors());

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

// Product Schema
const productSchema = new mongoose.Schema({
name: String,
price: Number,
category: String,
inStock: Boolean
});

const Product = mongoose.model('Product', productSchema);

// CRUD Endpoints
app.get('/products', (req, res) => {
Product.find().then(products => res.json(products));
});

app.post('/products', (req, res) => {
const newProduct = new Product(req.body);
newProduct.save().then(product => res.json(product));
});

app.put('/products/:id', (req, res) => {
Product.findByIdAndUpdate(req.params.id, req.body).then(() => res.json({ success: true }));
});

app.delete('/products/:id', (req, res) => {
Product.findByIdAndDelete(req.params.id).then(() => res.json({ success: true }));
});

// Endpoint to serve the HTML
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Men's Wear eCommerce</title>
</head>
<body>
<h1>Manage Products</h1>
<form id="product-form">
<label>Name:</label>
<input type="text" id="name" required><br>
<label>Price:</label>
<input type="number" id="price" required><br>
<label>Category:</label>
<input type="text" id="category" required><br>
<label>In Stock:</label>
<input type="checkbox" id="inStock"><br>
<input type="submit" value="Add Product">
</form>
<h2>Products</h2>
<div id="products"></div>
<script>
// Function to load products
function loadProducts() {
fetch('/products').then(res => res.json()).then(data => {
const productsDiv = document.getElementById('products');
productsDiv.innerHTML = '';
data.forEach(product => {
const productDiv = document.createElement('div');
productDiv.innerHTML = \`
<strong>\${product.name}</strong> - \${product.price} - \${product.category} - In Stock: \${product.inStock}
\`;
productsDiv.appendChild(productDiv);
});
});
}

// Function to add product
document.getElementById('product-form').addEventListener('submit', function(e) {
e.preventDefault();

const product = {
name: document.getElementById('name').value,
price: document.getElementById('price').value,
category: document.getElementById('category').value,
inStock: document.getElementById('inStock').checked,
};

fetch('/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(product),
})
.then(() => {
loadProducts();
document.getElementById('product-form').reset();
});
});

loadProducts();
</script>
</body>
</html>
`);
});

app.listen(3000, () => console.log('Server running on port 3000'));


Step 8: Creating the HTML and CSS Front-End

Create an index.html file with the following content:
htmlCopy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Men's Wear Shop</title>
<style>
/* Add your CSS styling here */
</style>
</head>
<body>
<h1>Men's Wear Shop</h1>
<form id="add-product-form">
<input type="text" id="name" placeholder="Name">
<input type="number" id="price" placeholder="Price">
<input type="text" id="category" placeholder="Category">
<input type="checkbox" id="inStock"> In Stock
<button type="submit">Add Product</button>
</form>
<div id="products"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>

Step 9: Connecting the Front-End to the Backend with AJAX

Create a new file app.js, and add the following code:
javascriptCopy code
// Function to load products
function loadProducts() {
$.get('http://localhost:3000/products', function(products) {
$('#products').empty();
products.forEach(product => {
// Display the product on the page
// Add buttons for updating and deleting
});
});
}

// Function to add a product
$('#add-product-form').submit(function(e) {
e.preventDefault();
const product = {
name: $('#name').val(),
price: $('#price').val(),
category: $('#category').val(),
inStock: $('#inStock').is(':checked')
};

$.post('http://localhost:3000/products', product, function() {
loadProducts();
$('#add-product-form')[0].reset();
});
});

// Add functions for updating and deleting products using $.ajax

// Load products on page load
loadProducts();

Step 10: Running the Application

Start MongoDB
Start the backend server:
rubyCopy code
$ node server.js
Open index.html in a browser or use a development server to host the frontend.

Conclusion

You have successfully built a front-end web page with HTML and CSS, connected to the MongoDB database through microservices and AJAX, and performed CRUD operations. You can further expand the application by adding more features and styling to fit the needs of your men's wear eCommerce website.
vbnetCopy code

This workbook provides a complete guide from the backend to the frontend to imple
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.