INSERT INTO only if Name and Location are NOT identical

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)

Answer №1

the proper format for SQL :

INSERT INTO camping_sites (name, location, max_length, elevation, number_of_sites, pad_type) 
SELECT ($1, $2, $3, $4, $5, $6)
WHERE NOT EXISTS(SELECT 1 from camping_sites where name =$1 AND location =$2)

or if there is a unique index on the name and location columns, you can utilize on conflict:

INSERT INTO camping_sites (name, location, max_length, elevation, number_of_sites, pad_type) 
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT unique_index DO NOTHING

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comet: showcase nested object on the client side using handlebars

Received JSON from helper : { "perms": [ { "userId": "rA5s5jSz7q9ZSCcNJ", "perms": [ { "moduleName": "Gallery", "container": { "ImageUpload": { ...

Using SailsJS to populate attributes transmitted through socket.io's publishUpdate event

Utilizing the built-in socket capabilities of SailsJS has proved to be quite effective for me so far. However, I've encountered a challenge that I haven't been able to find any information on. In my model, I have set it up to populate certain at ...

Detect both single and double click events on a single Vue component with precision

I did some online research but couldn't find a clear answer. However, I came across this article -> Since I didn't quite understand the solution provided, I decided to come up with my own inspired by it. detectClick() { this.clickCount += ...

"Angular ng-repeat: Restrict all items from being interacted with, except

I have a collection of items, each wrapped in a div element. I am trying to display only the first item as enabled while disabling the rest. AngularJs angular.module('example', []) .controller('myCtrl', function Ctrl($scope) { $sc ...

What is the best approach to integrate setTimeout() functions in Mocha test scenarios?

I'm working on a Mocha / Node.js test and I need to introduce a delay using setTimeout before executing a specific block of code. Is there a way to achieve this? It seems that setTimeout() does not function as expected within a Mocha test case. (I u ...

Enhance Bootstrap modals by automatically adjusting the background shadow mask when resizing or changing the content within the modal window

Incorporated within my bootstrap modal window is a form alongside a link that triggers the jQuery functionality of .slideToggle(). By interacting with this link, a concealed div expands. Consequently, the size of the modal popover becomes fluid. Upon click ...

The functionality of Jquery ceases to work once a setTimeout function is implemented

I need some help getting a series of functions to be delayed by 2 seconds using setTimeout. For some reason, whenever I try to implement this, the code stops executing altogether. I've double-checked the syntax and everything seems fine because it wor ...

What is the best way to deploy a REST API utilizing an imported array of JavaScript objects?

I have been using the instructions from this helpful article to deploy a Node REST API on AWS, but I've encountered a problem. In my serverless.yml file, I have set up the configuration for the AWS REST API and DynamoDB table. plugins: - serverless ...

Issue with Modal functionality in Internet Explorer 9

Check out the URL of a page that functions properly in Firefox, Chrome, and Safari, but is experiencing issues in IE 9. Upon page load, a modal displays a banner. The modal I am using can be found at Although the script appears to be correct, I have not ...

What is causing the addListener function in the events class to malfunction?

I am a beginner in the world of node.js and attempting to execute this piece of code: var eventlib= require('events'); var emitter= new eventlib(); eventlib.addListener('MessageEvent', function() { console.log('Registered the ...

Issues with AngularJS Filters malfunctioning

After watching some AngularJS videos and attempting to apply a filter to a list of bookmark categories, I'm having trouble loading the main content. At the moment, I haven't implemented views in my code and would like it to remain view-less for n ...

How to Turn Off Depth Testing in Three.js

I am currently using an EffectComposer in my project: renderer = new THREE.WebGLRenderer(); renderer.setDepthTest(false); ... composer = new THREE.EffectComposer( renderer); However, I noticed that when I attempt to disable the depth test with the follow ...

What could be the reason my Backbone view is failing to render?

Can anyone help me troubleshoot why this template isn't rendering properly in my backbone views? Any insights would be greatly appreciated! Below, I've included the code from my jade file for the views and the main.js file for the backbone js scr ...

Exploring D3.js version 4.10: Leveraging x-axis timescale with Data retrieval using XMLHttpRequest

I'm currently working with D3.js version 4 and encountering two separate issues. Firstly, I have retrieved data using XMLHTTPRequest which includes a name, an identifying number, and additional data. After my ajax request, the structure of the data ap ...

Set up Node.js application to allow CORS for designated endpoint(s) exclusively

I am currently facing a dilemma with my Node application and how to handle cross-origin resource sharing. In the past, I have used a PHP proxy to bypass this issue when calling endpoints from JavaScript/AJAX. However, I am now looking to streamline the pro ...

Utilizing AngularJS to iterate through an array of dictionaries

Within a specific section of my HTML code, I am initializing a scope variable like this: $scope.my_data = [ { c1: "r1c1", c2: "r1c2", c3: "r1c3", ...

Sending out a command does not equate to establishing Redux with an outcome

I've been grappling with this issue for the past 18 hours and I'm at a loss to figure out what's causing the problem. My redux setup is working smoothly as it dispatches actions and receives state correctly for other components. However, in ...

stop a element from being removed from the document

Is there a way to stop an element from being removed using something similar to preventDefault()? For example: myNode.on("remove", (e) => { e.preventDefault(); }); I have tried using MutationObserver to detect the removal, but so f ...

Developing a photo gallery using ASP.NET MVC

I have been working on an ASP.NET MVC application for uploading and retrieving images from the client side, but unfortunately, it is not functioning properly. I suspect there may be an issue with the HttpGet method I have implemented. Feel free to take a ...

What is the best way to showcase only the most recent data that has been received

Hey there, I'm working on a way to display only the most recent message of the day, However, I'm facing an issue where my code is always selecting the first message instead of the latest one. Even though it's not the initial object in the ...