load data database data and show on the UI part-3
const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://abcmehedi5:WD1kd4J7lElqvmJN@cluster0.mbjz2.mongodb.net/?retryWrites=true&w=majority";
// const password = 'WD1kd4J7lElqvmJN'
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })) //for use in the form
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
const productcollection = client.db("organicdb").collection("products");
// Data read in Database start........
app.get('/products' , (req , res ) =>{
productcollection.find({})
.toArray((err , document) =>{
res.send(document)
})
})
// Data read in Database end........
});
app.listen(port, () => {
console.log("listen working")
})
html file ....................
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>This is node js node js mongo bd project</h1>
<form action="/addProduct" method="post">
<input type="text" placeholder="Name" name="name" id="">
<input type="text" placeholder="Price" name="price" id="">
<input type="text" placeholder="Quantity" name="quantity" id="">
<button type="submit">Add Product</button>
</form>
<div id="products">
</div>
<script>
// Data read in Database start........
fetch('/products')
.then(res => res.json())
.then(product => {
console.log(product)
const container = document.getElementById('products')
product.forEach(pd => {
const p = document.createElement('p')
p.innerHTML = `${pd.name} quantity: ${pd.quantity} price:${pd.price}`
container.appendChild(p)
});
})
// Data read in Database end........
</script>
</body>
</html>
No comments