I am trying to run the delete query from app.js file to postgresql database but every time I am getting error: invalid input syntax for integer: "undefined"
Below is my app.js file code:
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cons = require('consolidate'),
dust = require('dustjs-helpers'),
pg = require('pg-promise'),
pgdb = require('pg'),
app = express();
//DB Connection
const config = {
user: 'Nasreen',
database: 'Inventory1',
password: 'test',
port: 5432 //Default port, change it if needed
};
const pool = new pgdb.Pool(config);
//assign dust engine
app.engine('dust', cons.dust);
//set default ext
app.set('view engine', 'dust');
app.set('views', __dirname + '/views');
//set public folder
app.use(express.static(path.join(__dirname, 'public')));
//Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('SELECT * FROM "Products"', function (err, result) {
if (err) {
return console.error('error running query', err);
}
res.render('index', { Products: result.rows });
done();
});
});
});
app.post('/add', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('INSERT INTO "Products" ("Name", "Purchase_Qty", "Purchase_Rate") VALUES($1, $2, $3)',
[req.body.Name, req.body.Purchase_Qty, req.body.Purchase_Rate]);
done();
res.redirect('/');
});
});
app.delete('/delete/:ID', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('DELETE FROM "Products" WHERE "ID" = $1',
[req.params.ID]);
done();
res.sendStatus(200);
});
});
app.post('/edit', function (req, res) {
pool.connect(function (err, client, done) {
if (err) {
return console.error('error', err)
}
client.query('UPDATE "Products" SET "Name"= $1, "Purchase_Qty"= $2, "Purchase_Rate"= $3 WHERE "ID"= $4',
[req.body.Name, req.body.Purchase_Qty, req.body.Purchase_Rate, req.body.ID]);
done();
res.redirect('/');
});
})
INSERT is working fine with double quotes for column names and table name but delete and edit wont't work.
Can someone plz help!!
You don't need to quote the tables' names and the columns' names.
Change the delete statement to:
"DELETE FROM Products WHERE ID = '$1'";
Change the update statement to:
"UPDATE Products SET Name= '$1', Purchase_Qty= '$2', Purchase_Rate= '$3' WHERE ID= '$4'";
EDIT:
Try this:
client.query(`DELETE FROM "Products" WHERE "ID" = ${req.params.ID}`);
It's a function overloading for query. Using template string should solve the issue.
Instead of:
client.query('DELETE FROM "Products" WHERE "ID" = $1',[req.params.ID]);
Related
I have a form where a user is supposed to put in there nickname, the issue is I need the nickname to be unique, in that no one else should be able to make there nickname the same as someone elses. Is there a fix for this using only mongoDB and not mongoose?
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var PORT = 3332;
app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost/gtra", {
useNewUrlParser: true
});
var db = mongoose.connection;
db.once("open", function(cb) {
console.log("connection established");
});
app.post("/addname", (req, res) => {
var name = req.body.pickname;
var data = {
nickname: name
};
db.collection("dat").insertOne(data, function(err, coll) {
if (err) throw err;
console.log("rec estab");
res.redirect("/");
});
});
app.listen(PORT, function() {
console.log("server is up and running using port " + PORT);
});
You can check if there is already a username in the collection, if exists you can throw exception.
app.post("/addname", (req, res) => {
var data = {
nickname: req.body.pickname
};
db.collection("dat").findOne({ nickname: data.nickname }, function(err, doc) {
if (err) throw err;
if (doc) {
return res.status(400).send("Nickname already taken"); //or throw whatever you want
} else {
db.collection("dat").insertOne(data, function(err, coll) {
if (err) throw err;
console.log("rec estab");
res.redirect("/");
});
}
});
});
Another option is creating a unique index on the nickname field.
db.users.createIndex( { "nickname": 1 }, { unique: true } )
Change users to your collection name.
I have implemented a CRUD application similar to the one in this link - https://www.youtube.com/watch?v=voDummz1gO0&t=1445s and a TODO application similar to the one in this link - https://medium.com/#atingenkay/creating-a-todo-app-with-node-js-express-8fa51f39b16f. I added a href link in the addOrEdit.hbs page to index.ejs, both in the views folder and have added the code from the TODO to the CRUD. I then start the server using a bat file, mongodb compass community and node server.js, everything connects fine but I receive this error - "Failed to lookup view "employee/addOrEdit" in views directory..." Is this because I have added some code incorrectly to my server.js file or controller file. I thought it might be due the server.js file having the following - "app.set('view engine', 'hbs');
app.set('view engine', 'ejs');" as I do not know if its possible to set view engines as both hbs and ejs. Below is my code and folder/file structure, hope it helps!
Folder/file structure
server.js file
require('./models/db');
const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
const employeeController = require('./controllers/employeeController');
var app = express();
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');
app.set('view engine', 'ejs');
//render css files
app.use(express.static("public"));
app.listen(3000, () => {
console.log('Express server started at port : 3000');
});
app.use('/employee', employeeController);
employeeController.js file in the controller file
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Employee = mongoose.model('Employee');
//placeholders for added task
var task = ["complete presentation", "practise with nodejs"];
//placeholders for removed task
var complete = ["finish jquery"];
router.get('/', (req, res) => {
res.render("employee/addOrEdit", {
viewTitle: "Insert Module"
});
});
router.get('/test', (req, res) => {
res.render("employee/test");
});
//render the ejs and display added task, completed task
router.get("/index", function(req, res) {
res.render("index", { task: task, complete: complete });
});
router.post('/', (req, res) => {
if (req.body._id == '')
insertRecord(req, res);
else
updateRecord(req, res);
});
function insertRecord(req, res) {
var employee = new Employee();
employee.fullName = req.body.fullName;
employee.module = req.body.module;
employee.mobile = req.body.mobile;
employee.city = req.body.city;
employee.save((err, doc) => {
if (!err)
res.redirect('employee/list');
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("employee/addOrEdit", {
viewTitle: "Insert Module",
employee: req.body
});
}
else
console.log('Error during record insertion : ' + err);
}
});
}
function updateRecord(req, res) {
Employee.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
if (!err) { res.redirect('employee/list'); }
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("employee/addOrEdit", {
viewTitle: 'Update Module',
employee: req.body
});
}
else
console.log('Error during record update : ' + err);
}
});
}
router.get('/list', (req, res) => {
Employee.find((err, docs) => {
if (!err) {
res.render("employee/list", {
list: docs
});
}
else {
console.log('Error in retrieving module list :' + err);
}
});
});
function handleValidationError(err, body) {
for (field in err.errors) {
switch (err.errors[field].path) {
case 'fullName':
body['fullNameError'] = err.errors[field].message;
break;
case 'module':
body['moduleError'] = err.errors[field].message;
break;
default:
break;
}
}
}
router.get('/:id', (req, res) => {
Employee.findById(req.params.id, (err, doc) => {
if (!err) {
res.render("employee/addOrEdit", {
viewTitle: "Update Module",
employee: doc
});
}
});
});
router.get('/delete/:id', (req, res) => {
Employee.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
res.redirect('/employee/list');
}
else { console.log('Error in module delete :' + err); }
});
});
//post route for adding new task
router.post("/addtask", function(req, res) {
var newTask = req.body.newtask;
//add the new task from the post route
task.push(newTask);
res.redirect("/");
});
router.post("/removetask", function(req, res) {
var completeTask = req.body.check;
//check for the "typeof" the different completed task, then add into the complete task
if (typeof completeTask === "string") {
complete.push(completeTask);
//check if the completed task already exits in the task when checked, then remove it
task.splice(task.indexOf(completeTask), 1);
} else if (typeof completeTask === "object") {
for (var i = 0; i < completeTask.length; i++) {
complete.push(completeTask[i]);
task.splice(task.indexOf(completeTask[i]), 1);
}
}
res.redirect("/");
});
module.exports = router;
I am trying to link (href) my hbs page to a ejs page in my views folder. I have installed consolidate as seen in other tutorials via going to the directory npm install consolidate and have added the code var engines = require('consolidate'); and app.engine('handlebars', engines.handlebars); to my code but nothing works (I also know if you’re using “.ejs” extensions you don’t need to do anything). Can someone please help me out as I cannot view my pages due to this. I receive this error - "Failed to lookup view employee/addOrEdit in views directory...". I have added my folder/file structure below and code snippets. Thank you!
folder/file structure
server.js file
require('./models/db');
const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
var engines = require('consolidate');
const employeeController = require('./controllers/employeeController');
var app = express();
app.engine('handlebars', engines.handlebars);
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');
//render css files
app.use(express.static("public"));
app.listen(3000, () => {
console.log('Express server started at port : 3000');
});
app.use('/employee', employeeController);
employeeController.js file
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Employee = mongoose.model('Employee');
//placeholders for added task
var task = ["complete presentation", "practise with nodejs"];
//placeholders for removed task
var complete = ["finish jquery"];
router.get('/', (req, res) => {
res.render("employee/addOrEdit", {
viewTitle: "Insert Module"
});
});
router.get('/test', (req, res) => {
res.render("employee/test");
});
//render the ejs and display added task, completed task
router.get("/index", function(req, res) {
res.render("index", { task: task, complete: complete });
});
router.post('/', (req, res) => {
if (req.body._id == '')
insertRecord(req, res);
else
updateRecord(req, res);
});
function insertRecord(req, res) {
var employee = new Employee();
employee.fullName = req.body.fullName;
employee.module = req.body.module;
employee.mobile = req.body.mobile;
employee.city = req.body.city;
employee.save((err, doc) => {
if (!err)
res.redirect('employee/list');
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("employee/addOrEdit", {
viewTitle: "Insert Module",
employee: req.body
});
}
else
console.log('Error during record insertion : ' + err);
}
});
}
function updateRecord(req, res) {
Employee.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
if (!err) { res.redirect('employee/list'); }
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("employee/addOrEdit", {
viewTitle: 'Update Module',
employee: req.body
});
}
else
console.log('Error during record update : ' + err);
}
});
}
router.get('/list', (req, res) => {
Employee.find((err, docs) => {
if (!err) {
res.render("employee/list", {
list: docs
});
}
else {
console.log('Error in retrieving module list :' + err);
}
});
});
function handleValidationError(err, body) {
for (field in err.errors) {
switch (err.errors[field].path) {
case 'fullName':
body['fullNameError'] = err.errors[field].message;
break;
case 'module':
body['moduleError'] = err.errors[field].message;
break;
default:
break;
}
}
}
router.get('/:id', (req, res) => {
Employee.findById(req.params.id, (err, doc) => {
if (!err) {
res.render("employee/addOrEdit", {
viewTitle: "Update Module",
employee: doc
});
}
});
});
router.get('/delete/:id', (req, res) => {
Employee.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
res.redirect('/employee/list');
}
else { console.log('Error in module delete :' + err); }
});
});
//post route for adding new task
router.post("/addtask", function(req, res) {
var newTask = req.body.newtask;
//add the new task from the post route
task.push(newTask);
res.redirect("/");
});
router.post("/removetask", function(req, res) {
var completeTask = req.body.check;
//check for the "typeof" the different completed task, then add into the complete task
if (typeof completeTask === "string") {
complete.push(completeTask);
//check if the completed task already exits in the task when checked, then remove it
task.splice(task.indexOf(completeTask), 1);
} else if (typeof completeTask === "object") {
for (var i = 0; i < completeTask.length; i++) {
complete.push(completeTask[i]);
task.splice(task.indexOf(completeTask[i]), 1);
}
}
res.redirect("/");
});
module.exports = router;
You need to add both engines, ejs and express-handlebars in your package.json file
npm i ejs
npm i express-handlebars
Import dependency in Server.js file
const ejs = require('ejs');
const exhbs = require('express-handlebars');
Set engine to your server.js file
app.set('view engine', 'ejs');
app.engine('handlebars', exhbs());
app.set('view engine', 'handlebars');
For rendering template, you need to set the file extension
res.render('heyy.handlebars');
res.render('index.ejs');
This is your Folder Structure
Inside main.handlebars and inside body add {{{body}}} inorder to mark where layout should insert page
I am currently having trouble with showing my aggregation records. I wanted to show the summed up value for all the documents but its not showing. It keeps showing me the Records not found only. I don't know where i have gone wrong. Someone help me out.
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('meibanlist', ['contact']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/meibanlist', function (req, res) {
console.log('I received a GET request');
db.meibanlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/meibanlist', function (req, res) {
console.log(req.body);
db.meibanlist.insert(req.body, function(err, doc) {
res.json(doc);
});
});
app.delete('/meibanlist/', function (req, res) {
console.log();
db.meibanlist.remove(function (err, doc) {
res.json(doc);
});
});
app.get('/meibanlist/', function (req, res) {
console.log();
db.meibanlist.findOne(function (err, doc) {
res.json(doc);
});
});
app.put('/meibanlist/', function (req, res) {
console.log(req.body.machine_Id);
db.meibanlist.findAndModify({
query: {_id: mongojs.machine_Id},
update: {$set: {machine_Id: req.body.machine_Id, air_Temp: req.body.air_Temp, water_Temp: req.body.water_Temp, heat_Temp: req.body.heat_Temp, room_Temp: req.body.room_Temp, date:req.body.date, time: req.body.time}},
new: true}, function (err, doc) {
res.json(doc);
}
);
});
db.contact.aggregate([{$group: {machine_Id : "$machine_Id", air_Temp : {$sum : "$likes"}}}], function(err, meibanlist) {
if( err || !meibanlist ) console.log("Record not found");
else meibanlist.forEach (function(machine_Id){
console.log(machine_Id);
});
});
app.listen(3000);
console.log("Server running on port 3000");
I'm using Express with Socket.io but I can't figure out how to use SocKet.io in Express routes.
I end up doing this in "app.js"
...
...
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var server = http.createServer(app);
var io = require("socket.io").listen(server);
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/cmp', function(request, response) {
var client = new pg.Client("pg://user:pass#127.0.0.1/db_name");
client.connect(function(err) {
// Get the product_id and bid
var product_id = request.body.product_id;
var bid = request.body.bid.split('b')[1];
// If not get the connection
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('select 1 from product_bid where product_id = $1 and number_bid = $2', [product_id, bid], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (result.rowCount == 1) {
// do not insert
} else {
// insert
// Insert to the DB
client.query('insert into product_bid (product_id, number_bid) values ($1, $2)', [product_id, bid], function(err, result) {
if(err) {
return console.error('error running query', err);
}
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
client.end();
});
}
});
});
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
// ---------------
io.on('connection', function(socket){
console.log("alguem se ligou!");
socket.emit('event_from_server', {message: 'conectou-se ao servidor'});
});
How can I define the route to "/cmp" like this and passing the var "io" inside?
app.post('/cmp', routes.cmp);
So that in "/routes/cmp.js" I can do something like this:
exports.cmp = function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
};
Some clues?
How about a higher order function?
exports.cmp = function(io) {
return function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
}
};
and then
app.post('/cmp', routes.cmp(io));
As another option, I'll sometimes format my routes in the following format:
var routes = require('./routes/routes');
routes(app, io);
And then define routes as
module.exports = function(app, io) {
app.post('/cmp', function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
})
};
You can use simple middleware before routes, and then use in res object
app.use((req, res, next) => {
res.io = io
next()
})