I'm facing an issue with adding a record to my psql table only if it has a unique Name and Location. Currently, the code I have is able to insert a record if the entry doesn't already exist in the table (based on name or location). However, when the name already exists, my server throws an error in response to the query. Below is the snippet of my code:
app.post("/addCampground", async (req, res) => {
const name = req.body.name;
const location = req.body.location;
const leng = req.body.maxlength;
const elev = req.body.elevation;
const site = req.body.sites;
const pad = req.body.pad;
try{
const template = "INSERT INTO campgrounds (name, location, maxlength, elevation,
sites, padtype) VALUES ($1, $2, $3, $4, $5, $6) SELECT name, location WHERE NOT
EXISTS(SELECT name, location from campgrounds where name =$1 AND location =$2)";
console.log(template);
const response = await pool.query(template, [name, location, leng, elev, site, pad]);
res.json({status: "added", results:{name:name, location:location} });
}catch (err){
res.json({status: "campground already in database"});
}
})
The specific query causing the problem is:
const template = "INSERT INTO campgrounds (name, location, maxlength, elevation, sites, padtype) VALUES
($1, $2, $3, $4, $5, $6) SELECT name, location WHERE NOT EXISTS(SELECT name, location from campgrounds
where name =$1 AND location =$2)";
const response = await pool.query(template, [name, location, leng, elev, site, pad]);
Here's the error message that appears when trying to add a record with a matching Name but different Location:
TypeError: cb is not a function
at Query.callback (/home/sbeg/db-class-350/practice/task4/node_modules/pg-pool/index.js:376:18)
at Query.handleError (/home/sbeg/db/db-class-350/practice/task4/node_modules/pg/lib/query.js:128:19)
at Client._handleErrorMessage (/home/sbeg/db-class-350/practice/task4/node_modules/pg/lib/client.js:335:17)
at Connection.emit (events.js:315:20)
at /home/sbeg/db-class-350/practice/task4/node_modules/pg/lib/connection.js:115:12
at Parser.parse (/home/sbeg/db-class-350/practice/task4/node_modules/pg-protocol/dist/parser.js:40:17)
at Socket.<anonymous> (/home/sbeg/db-class-350/practice/task4/node_modules/pg-protocol/dist/index.js:10:42)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)