1st=> install mongo dB client -
npm install --save mongo
2nd=> create an atlas cluster
or connect to the localhost (this will be done in a separate session)
(I will be using the local connection)
3rd=>
setup the database.js file
(With connection Pooling)
const mongodb = require("mongodb");
const mongoClient = mongodb.MongoClient;
let _db; make a single db instance -> singleton design pattern
const mongoConnect = () => {
mongoClient
.connect("mongodb://localhost:27017/nodefirst", {
if you have the cluster uri paste it here
nodefirst is the db name -> do not need to pre-create
useUnifiedTopology: true,
})
.then((client) => {
console.log("connected.!");
_db = client.db();
})
.catch((err) => {
console.log("Error=>" + err);
process.exit(1);
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw "No Databases
Found...!!!";
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
4th=> in app.js
const mongoConnect = require("./helper/database").mongoConnect; //import the db file
mongoConnect(); //call the db creation
app.listen(3000);
console.log("Server running at http://127.0.0.1:3000/");
5th=> Adding data and retrieving
in
Products Model
const getDb = require("../helper/database").getDb;
class Product {
constructor(title, price, description, imgUrl) {
this.title = title;
this.price = price;
this.description = description;
this.imgUrl = imgUrl;
}
save() {
const db = getDb(); one DB connection-> Singleton
return db
.collection("products")
.insertOne(this)
.then((result) => {
console.log("result=> " + result);
})
.catch((err) => {
console.log(err);
});
}
static fetchAll() {
const db = getDb();
find retrieves a cursor ->imp in pagination
in
here we convert all data into an array
later
we will do with the cursor
return db
.collection("products")
.find()
.toArray()
.then((products) => {
console.log(products);
return products;
})
.catch((err) => {
console.log(err);
});
}
}
module.exports = Product;
6th=>
In controller (same as previous)
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imgUrl = req.body.imgUrl;
const price = req.body.price;
const description = req.body.description;
const product = new Product(title, price, description, imgUrl);
product
.save()
.then((result) => {
console.log("Succsfully
addeddd..!!!!");
res.redirect("/");
})
.catch((err) => {
console.log(err);
});
};
Fetching
the Data
exports.getProducts = (req, res, next) => {
Product.fetchAll()
.then((products) => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
hasProducts: products.length > 0,
active: "products",
});
})
.catch((err) => {});
};

0 Comments