DEV Community

Joshcodes
Joshcodes

Posted on

Mongo db boiler plate

Top comments (9)

Collapse
 
joshcal profile image
Joshcodes • Edited

<!DOCTYPE html>




Universal CRUD Template
<br> /* Simple styling for readability */<br> body { font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif; max-width: 600px; margin: 40px auto; line-height: 1.6; }<br> .card { border: 1px solid #ddd; padding: 20px; border-radius: 8px; box-shadow: 2px 2px 10px rgba(0,0,0,0.1); }<br> input { padding: 8px; margin-right: 5px; border: 1px solid #ccc; border-radius: 4px; }<br> button { cursor: pointer; padding: 8px 15px; border: none; border-radius: 4px; background: #28a745; color: white; }<br> button.delete-btn { background: #dc3545; margin-left: 10px; }<br> button.edit-btn { background: #007bff; margin-left: 10px; }<br> ul { list-style: none; padding: 0; margin-top: 20px; }<br> li { background: #f9f9f9; border-bottom: 1px solid #eee; padding: 15px; display: flex; align-items: center; justify-content: space-between; }<br>

<div class="card">
    <h2>📦 Data Management</h2>

    <form id="itemForm">
        <input type="text" id="itemName" placeholder="Item Name" required>
        <input type="number" id="itemPrice" placeholder="Price" required>
        <button type="submit" id="addBtn">Add to List</button>
    </form>

    <ul id="display-list">
        </ul>
</div>

<script>
    /**
     * CONFIGURATION
     * Change 'API_URL' to your backend route (e.g., http://localhost:5000/api/items)
     */
    const API_URL = '/items'; 
    const addBtn = document.getElementById('addBtn');
    const listContainer = document.getElementById('display-list');

    // --- 1. CREATE (POST) ---
    // Triggered when user clicks the "Add" button
    addBtn.addEventListener('click', async (e) => {
        e.preventDefault(); // Prevents page from refreshing on form submit

        const name = document.getElementById('itemName').value;
        const price = document.getElementById('itemPrice').value;

        // Simple validation
        if (!name || !price) return alert("Please fill all fields");

        // Sending data to server
        await fetch(API_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name, price }) // Convert JS object to JSON string
        });

        // Reset UI
        document.getElementById('itemName').value = '';
        document.getElementById('itemPrice').value = '';
        loadItems(); // Refresh the list
    });

    // --- 2. READ (GET) ---
    // Fetches data from the database and renders it to the HTML
    async function loadItems() {
        try {
            const res = await fetch(API_URL);
            const data = await res.json(); // Data expected as an Array of Objects

            listContainer.innerHTML = ''; // Clear existing list to prevent duplicates

            data.forEach(item => {
                const li = document.createElement('li');
                // item._id is the standard unique ID from MongoDB
                li.innerHTML = `
                    <div>
                        <strong>${item.name}</strong> 
                        <span> - ₹${item.price}</span>
                    </div>
                    <div>
                        <button class="edit-btn" onclick="updateItem('${item._id}')">Edit</button>
                        <button class="delete-btn" onclick="deleteItem('${item._id}')">Delete</button>
                    </div>
                `;
                listContainer.appendChild(li);
            });
        } catch (err) {
            console.error("Error loading items:", err);
            listContainer.innerHTML = '<li>Error loading data. Check console.</li>';
        }
    }

    // --- 3. DELETE (DELETE) ---
    // Removes an item based on its unique ID
    async function deleteItem(id) {
        if (confirm("Are you sure you want to delete this?")) {
            await fetch(`${API_URL}/${id}`, { 
                method: 'DELETE' 
            });
            loadItems(); // Refresh the list
        }
    }

    // --- 4. UPDATE (PUT) ---
    // Updates a specific value (Price) using a prompt for simplicity
    async function updateItem(id) {
        const newPrice = prompt("Enter the new price:");

        if (newPrice !== null && newPrice !== "") {
            await fetch(`${API_URL}/${id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ price: Number(newPrice) })
            });
            loadItems(); // Refresh the list
        }
    }

    // --- INITIALIZATION ---
    // Runs once when the page first loads
    loadItems();

</script>
Collapse
 
joshcal profile image
Joshcodes

const express=require('express');
const mongoose=require('mongoose');
const cors=require('cors');
const app=express();
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
mongoose.connect('mongodb://127.0.0.1/myapp')
.then(()=>console.log('Connected to MongoDB'))
.catch(err=>console.error('Could not connect to MongoDB',err));
const itemSchema=new mongoose.Schema({
name:String,
price:Number
});
const Item=mongoose.model('Item',itemSchema);
app.post('/items',async(req,res)=>{
const item=new Item(req.body);
await item.save();
res.send(item);
});
app.get('/items',async(req,res)=>{
const items=await Item.find();
res.send(items);
});
app.delete('/items/:id', async (req, res) => {
await Item.findByIdAndDelete(req.params.id);
res.send("Deleted");
});

// UPDATE: Change an item's price by its ID
app.put('/items/:id', async (req, res) => {
const updatedItem = await Item.findByIdAndUpdate(
req.params.id,
{ price: req.body.newPrice },
{ new: true }
);
res.send(updatedItem);
});
const PORT=process.env.PORT || 3000;
app.listen(PORT,()=>{
console.log(Server is running on port ${PORT});
});

Collapse
 
joshcal profile image
Joshcodes

const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 1. Database Connection
const db = mysql.createPool({
host: 'localhost',
user: 'root', // Your MySQL username
password: 'password', // Your MySQL password
database: 'lab_db'
});

// 2. CREATE (POST)
app.post('/products', (req, res) => {
const { name, price, quantity, description } = req.body;
const sql = "INSERT INTO products (name, price, quantity, description) VALUES (?, ?, ?, ?)";
db.query(sql, [name, price, quantity, description], (err, result) => {
if (err) return res.status(500).send(err);
res.send({ id: result.insertId, ...req.body });
});
});

// 3. READ (GET)
app.get('/products', (req, res) => {
db.query("SELECT * FROM products", (err, results) => {
if (err) return res.status(500).send(err);
res.send(results);
});
});

// 4. UPDATE (PUT)
app.put('/products/:id', (req, res) => {
const { newPrice, newQuantity, newDescription } = req.body;
const sql = "UPDATE products SET price = ?, quantity = ?, description = ? WHERE id = ?";
db.query(sql, [newPrice, newQuantity, newDescription, req.params.id], (err, result) => {
if (err) return res.status(500).send(err);
res.send("Updated");
});
});

// 5. DELETE
app.delete('/products/:id', (req, res) => {
db.query("DELETE FROM products WHERE id = ?", [req.params.id], (err, result) => {
if (err) return res.status(500).send(err);
res.send("Deleted");
});
});

app.listen(3000, () => console.log("MySQL Server running on 3000"));

Thread Thread
 
joshcal profile image
Joshcodes

npm install mysql2
CREATE DATABASE lab_db;
USE lab_db;

CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
price DECIMAL(10, 2),
quantity INT,
description TEXT
);

Thread Thread
 
joshcal profile image
Joshcodes

const express =require('express');
const mongoose=require('mongoose');
const cors=require('cors');
const app=express();
app.use(express.json());
app.use(cors());
app.use(express.static('public'));
mongoose.connect('mongodb://localhost:27017/myapp')
.then(()=>console.log('Connected to MongoDB'))
.catch(err=>console.error('Could not connect to MongoDB',err));
const itemSchema=new mongoose.Schema({
name:String,
price:Number,
quantity:Number,
description:String
});
const product=mongoose.model('product',itemSchema);
app.get('/products',async(req,res)=>{
const products=await product.find();
res.send(products);
});
app.post('/products',async(req,res)=>{
const newProduct=new product(req.body);
await newProduct.save();
res.send(newProduct);
});
app.delete('/products/:id', async (req, res) => {
await product.findByIdAndDelete(req.params.id);
res.send("Deleted");
});
app.put('/products/:id', async (req, res) => {
try {
// Validation: Ensure the ID is present
if (!req.params.id || req.params.id === "undefined") {
return res.status(400).send("Invalid Product ID");
}

    const updatedProduct = await product.findByIdAndUpdate(
        req.params.id,
        { 
            price: Number(req.body.newPrice) || 0,
            quantity: Number(req.body.newQuantity) || 0,
            description: req.body.newDescription || ""
        },
        { new: true, runValidators: true }
    );

    if (!updatedProduct) {
        return res.status(404).send("Product not found in database");
    }

    res.send(updatedProduct);
} catch (err) {
    console.error('Mongoose Error:', err.message);
    res.status(500).send("Server Error: " + err.message);
}
Enter fullscreen mode Exit fullscreen mode

});
const PORT=process.env.PORT || 3000;
app.listen(PORT,()=>{
console.log(Server is running on port ${PORT});
});``

Thread Thread
 
joshcal profile image
Joshcodes

const API_URL='/products';
const addBtn=document.getElementById('addBtn');
const listContainer=document.getElementById('product-List');
addBtn.addEventListener('click', async (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const price = document.getElementById('price').value;
const quantity = document.getElementById('quantity').value;
const description = document.getElementById('description').value;
if (!name || !price || !quantity || !description) return alert("Fill all fields");
await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, price, quantity, description })
});
document.getElementById('name').value = '';
document.getElementById('price').value = '';
document.getElementById('quantity').value = '';
document.getElementById('description').value = '';
loadProducts();
});
async function loadProducts() {
try {
const res = await fetch(API_URL);
const data = await res.json();
listContainer.innerHTML = '';
data.forEach(product => {
const li = document.createElement('li');
li.style.borderBottom = "1px solid #ddd";
li.innerHTML = `
<div>
<strong>${product.name}</strong>
<p>Price: $${product.price}</p>
<p>Quantity: ${product.quantity}</p>
<p>Description: ${product.description}</p>
</div>
<div>
<button onclick="updateProduct('${product._id}')">Edit</button>
<button onclick="deleteProduct('${product._id}')" style="background:red; color:white">Delete</button>
</div>
`;
listContainer.appendChild(li);
});
} catch (err) {
console.error('Error loading products:', err);
}
}
async function deleteProduct(id) {
if (confirm("Delete this product?")) {
await fetch(`${API_URL}/${id}`, { method: 'DELETE' });
loadProducts();
}
}
async function updateProduct(id) {
const newPrice = prompt("Enter new price:");
const newQuantity = prompt("Enter new quantity:");
const newDescription = prompt("Enter new description:");
if (newPrice === null) return;
await fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price: Number(newPrice), quantity: Number(newQuantity), description: newDescription })
});
loadProducts();
}
loadProducts();

Thread Thread
 
joshcal profile image
Joshcodes
Name Price Quantity Description Actions

async function loadProducts() {
const res = await fetch('/products');
const data = await res.json();

const tableBody = document.getElementById('product-table-body');
tableBody.innerHTML = ''; // Clear the table

data.forEach(item => {
    const row = document.createElement('tr');

    row.innerHTML = `
        <td>${item.name}</td>
        <td>₹${item.price}</td>
        <td>${item.quantity}</td>
        <td>${item.description || 'N/A'}</td>
        <td>
            <button onclick="updateProduct('${item._id}')">Edit</button>
            <button onclick="deleteProduct('${item._id}')" style="color:red">Delete</button>
        </td>
    `;
    tableBody.appendChild(row);
});
Enter fullscreen mode Exit fullscreen mode

}

Thread Thread
 
joshcal profile image
Joshcodes




































Name Price Quantity Description Actions
``
Collapse
 
joshcal profile image
Joshcodes

mongodb://localhost:27017