Performing a mass update on several columns in a PostgreSQL table using pg and express.js with just one query

I have a database with PostgreSQL that includes a table called events. My goal is to enable a user to update any column or multiple columns in this table through input. The issue I am facing with the current code is that when a user updates, for instance, the wedding_name column and leaves the others blank, the row gets successfully updated with the new value only on the specified column. However, the remaining columns become empty because they did not receive any input. Ideally, I would like to be able to update individual columns without affecting the untouched ones in a single query. Thank you.

modifyEvent:async(req, res)=>{
        try {
           const eventId= req.params.eventId 
           const {weddingName,groom,bride,location,date,}=req.body
           const updatedEvent=pool.query('UPDATE events SET wedding_name=$1,bride_name=$2,groom_name=$3,wedding_location=$4,wedding_date=$5 WHERE wedding_id=$6',[
               weddingName,bride,groom,location,date,eventId
           ])
           res.json(updatedEvent)
        } 
        catch (error) {
            console.log(error.message)
        }
    }

Answer №1

Here's a potential solution to update event details in the database:

const updatedEvent = pool.query('UPDATE events SET wedding_name=COALESCE($1, wedding_name), bride_name=COALESCE($2, bride_name), groom_name=COALESCE($3, groom_name), wedding_location=COALESCE($4, wedding_location), wedding_date=COALESCE($5, wedding_date) WHERE wedding_id=$6',[weddingName,bride,groom,location,date,eventId])

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

Requests from external sources are being overlooked by Node.js running on a virtual machine

This is my first time working with nodejs and express, so please bear with me if this question seems basic. I recently set up nodejs and express on my Debian virtual machine and created a hello-world application. To run it, I used the command: DEBUG=myap ...

Validate file input using express-validator - A step-by-step guide

Using express-validator to validate input, I have a method in my controller that adds new pictures to the database. Here's the relevant code snippet: function createPicture(req, res) { req.checkBody('title', `The title must not be empty.`) ...

When you make a POST request to an express API, the properties are not clearly defined

Just getting into Vue.JS and experimenting with creating a basic MEVN to-do list app for practice. I keep encountering an issue when trying to send a POST request to my express server, receiving the error message: TypeError: Cannot read properties of unde ...

Creating dynamic databases in real-time with Node, EJS, and Firebase

As I venture into learning Node JS, I am currently transitioning from a client-side chat application to a server-side one. Previously, when my app was solely client-side, any modifications to the database automatically triggered data reload in a div, provi ...

The system is unable to locate the specific file or directory that is causing an error in the Pug

After deploying to Heroku, I encountered an error that was not present when running the application locally. Here is the message displayed in the browser: https://i.stack.imgur.com/CbhaV.png This is my display.pug file: extends ../LoginLayout/LoginLayou ...

Mongoose: utils.populate function encountered an error with an invalid path. The expected input type is a string, but instead received a value of

Although I am not a complete novice with Populate user, I seem to be facing some issues now. My current dilemma involves populating my designerId, which is of type ObjectId. Please review the code snippet from my route below: ordersAdminRouter.route(&apo ...

Struggling to make EJS button functional on the template

I am currently facing an issue with a loop that populates a webpage with multiple items, each containing an image, text, button, and a unique ID associated with it. Although I have written a function to retrieve the ID and plan name when the button is clic ...

Handling Errors in Node.js with Express

To access the complete repository for this project, visit: https://github.com/austindickey/FriendFinder After downloading the directory, follow the instructions in the ReadMe to set it up on your computer. Encountering an issue where my survey.html page ...

Nodemailer contact form malfunctioning

I've been working on setting up a contact form in React and utilizing nodemailer to send messages to my email, but I seem to be encountering some issues. I have a server.js file located in the main folder along with Mailer.js which contains the form c ...

The issue of passing a sequelize model instance to a service within an express.js environment has been causing complications

I am struggling to access the findById function of CRUDService in ItemService. While I am able to get a response from the readAll function, I am facing issues with the findById function. It seems that the dao object being passed to CRUDService from ItemSer ...

Unable to establish connection with Redis - Error: Connection refused on address 127.0.0.1:6379

My current task involves coding in Express.js, executed on an AWS Elastic Beanstalk instance, attempting to establish a connection with an AWS ElastiCache instance using Redis. However, I am encountering the following error message: web: Error connecting t ...

Is there a way to automate the distribution of tasks to users in order to ensure that each user receives an equal number of assignments?

I'm in the process of developing an automated task manager that assigns tasks to users based on their role. Currently, I'm randomly selecting a user with the same role as the task from the list of users and assigning the task to them using math.r ...

Transitioning to HTTPS for a stationary React application hosted on the Google App Engine

I have a nodejs app hosted in GAE flexible environment. We've successfully set up the google-managed SSL and the https route is working as expected. However, due to serving the application statically, we are facing challenges in enforcing a redirect ...

What are the steps to integrate Webpack into an EJS Reactjs Express MongoDb application?

I have incorporated EJS, Express/NodeJs, and MongoDB into the project, along with ReactJs as an addition. My next step is to introduce Webpack for bundling both EJS and ReactJs files together. Although the end goal is to transition the p ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

What is the process for changing a value in a mongoose document?

Recently, I encountered a challenge in modifying someone else's code. Instead of deleting a MongoDB document, my task is to update it. Let's take a look at the original code snippet: const docs = await docsModel.find({}); for (const doc of doc ...

"The loop functionality appears to be malfunctioning within the context of a node

Below is the code snippet: for (var j in albums){ var album_images = albums[j].images var l = album_images.length for ( var i = 0; i < l; i++ ) { var image = album_images[i] Like.findOne({imageID : image._id, userIDs:user ...

Is it a good idea to utilize triggers when bootstrapping an application?

Currently, I am in the process of developing an internal web application for managing building parts. The main focus is on a table containing projects that are interconnected with other tables. Whenever a new project is created by a user, my goal is to ini ...

Make Connections between Schemas with MongoDB, Express, and Mongoose

I need to establish relationships between my schemas in the "Movie" entity so that I can access information from other entities like: Category Actor Director Studio Right now, I am testing with categories. This is the code I have written: controllers/m ...

Use the Nodejs HTTP.get() function to include a custom user agent

I am currently developing an API that involves making GET requests to the musicBrainz API using node.js and express. Unfortunately, my requests are being denied due to the absence of a User-Agent header, as stated in their guidelines: This is the code sn ...