let express = require('express');
let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/";
let router = express.Router();
let obj = null;
router.get('/', function (req, res) {
getDfroMongo(res);
});
function getDfroMongo(res) {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
//Sort the result by name:
var sort = { car: 1 };
dbo.collection("customers").find().sort(sort).toArray(function (err, result) {
if (err) throw err;
obj = result;
// db.close();
res.render(__dirname + '/views/mongo', { result: obj });
});
});
}
router.post('/', function (req, response) {
switch (req.body.data) {
case "add":
let car = req.body.car;
let model = req.body.model;
let year = req.body.year;
let myimg = req.body.img;
obj = { car: car, model: model, year: year, img: myimg };
if (car != "" && model != "" && year != "" && myimg != "") {
console.log(obj);
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { Car: car, Model: model, Year: year, img: myimg };
dbo.collection("customers").insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("1 document inserted");
// db.close();
getDfroMongo(response);
});
});
}
else
console.log('field missed');
break;
case "delete":
let carName = req.body.carName;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { Car: carName };
dbo.collection("customers").deleteOne(myquery, function (err, obj) {
if (err) throw err;
console.log("1 document deleted");
// db.close();
getDfroMongo(response);
});
});
break;
case "update":
upcar = req.body.car;
upmodel = req.body.model;
upyear = req.body.year;
upimg = req.body.img;
upcarName = req.body.carName;
// obj = { car: upcar, model: upmodel, year: upyear, img: upimg, carName: upcarName };
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { Car: upcarName };
var newvalues = { $set: { Car: upcar, Model: upmodel,Year:upyear,img:upimg } };
dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
// db.close();
getDfroMongo(response);
});
});
break;
default:
break;
}
});
module.exports=router;