Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank.

The SELECT queries in use are as follows:

-- Retrieve all users
SELECT * FROM users
ORDER BY user_id ASC;

-- Retrieve a specific user
SELECT * FROM users
WHERE user_id = $1;

When it comes to INSERT statement execution, any unspecified value defaults to NULL:

INSERT INTO users (name, username, email, phone, website)
VALUES ($1, $2, $3, $4, $5) RETURNING *;

The POST request's callback function is structured as follows:

const createUser = async (req, res, next) => {
  const { name, username, email, phone, website } = req.body;

  try {
    const create = await db.query(insertUser, [
      name,
      username,
      email,
      phone,
      website,
    ]);
    res
      .status(201)
      .json({ message: "User Created Successfully!", user: create.rows[0] });
  } catch (err) {
    // Handling UNIQUE constraint violation
    if (err.code == "23505") {
      uniqueConstraintError(err, next);
    } else {
      serverError(err, next);
    }
  }
};

The insertUser variable stores the PostgreSQL statement.

In cases where the user data is added without specifying phone and website fields, the GET requests still display these as NULL:

{
   "user_id": 10,
   "name": "Bruce Wayne",
   "username": "Batman",
   "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d1d2c7f3d0d2c5d69dd0dcde">[email protected]</a>",
   "phone": null,
   "website": null
}

Is there a method to conceal these NULL values in the SELECT statements and obtain output similar to this?

{
   "user_id": 10,
   "name": "Bruce Wayne",
   "username": "Batman",
   "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7e7d685c7f7d6a79327f737f7775">[email protected]</a>"
}

Answer №1

Utilize the json_strip_nulls function within Postgres for removing null values

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

What is the best way to deactivate buttons with AngularJS?

I have a situation where I need to disable the save button in one function and permanently disable both the save as draft and save buttons in another function using AngularJS. How can I accomplish this task with the disable functionality in AngularJS? Her ...

Exploring the functionality of using a URL as a parameter in the res.download() method in Express

While I was looking at an expressjs example, I found the following code snippet: res.download('/report-12345.pdf'); which is supposed to prompt the user for download. However, when I tried passing a URL as a parameter, it didn't work as expe ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...

What is causing my server to mysteriously alter the style of index.html?

After setting up a node, express, react app, I realized that when express serves static content like my CSS file, the source of the index.html shows an additional style tag in the head section: <style type="text/css">* {}</style> I confirme ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

Ways to change a value into int8, int16, int32, uint8, uint16, or uint32

In TypeScript, the number variable is floating point by default. However, there are situations where it's necessary to restrict the variable to a specific size or type similar to other programming languages. For instance, types like int8, int16, int32 ...

Removing custom scrollbars using jQuery from an element

Utilizing mCustomScrollbar with jQuery UI dialog boxes. When attempting to initialize mCsutomScrollbar on $(window).load as instructed, it fails because the dialogs are not yet visible. As a workaround, I've had to initiate mCsutomScrollbar on the op ...

"pre and post" historical context

Is there a way to create a stunning "Before and After" effect using full-sized background images? It would be amazing if I could achieve this! I've been experimenting with different examples but can't seem to get the second 'reveal' di ...

React - Exploring the depths of functional components

Picture this: a straightforward form that showcases several unique components with customized layouts. The custom components include: <UsernameInput />, <PasswordInput />, <DateTimePicker />, <FancyButton />, <Checkbox /> Th ...

Troubleshooting Async Issues in Node.js

I am encountering an issue with my node.js app structure, which is as follows: async.forever( function(callback) { async.series([ function(callback) { SomeFunction1(function(err, results) { if (err) callback(err); ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

Tips for maximizing the effectiveness of the .bind(this) method in Meteor js

Hey there, I've got a question for you. How do we go about using the bind method in Meteor? Take a look at this code snippet below. It feels like there's some repetition going on that bothers me. Thank you so much for sharing your thoughts! Bi ...

Managing nested dependencies through npm

Seeking advice on effectively managing nested dependencies in npm. My current scenario involves running an app with express.js and express-mongostore in a nodeenv environment. Due to nodeenv, I have opted to globally npm all packages, leading them to be s ...

Only Chrome causing my JavaScript execution to freeze due to Ajax

When using Ajax, it is supposed to be asynchronous, but for some reason, it seems like it's either stopping or pausing my JavaScript execution and only resuming once the response is received. Here is an example of HTML value: <input value="foo" d ...

Avoid using single quotes in Postgres queries for a more secure Node.js application

Snippet from my node js code: var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite") VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')' My problem is inserting single quotes before JSON.stringify(r ...

Countdown to redirect or exit on Jquery mobile "pageshow" and "pagehide" events

Looking to implement a 30-second countdown on a Jquery Mobile page with specific requirements: (1) Countdown begins on pageshow (2) Redirects to new page when countdown expires (3) If user navigates away (pagehide) before countdown finishes, the timer fun ...

SQLAlchemy query to retrieve rows where the array column does not include a specific value

I have 1001 records in my database. # 1001 print len(Session.query(MyTable).all()) Within these records, one contains the word 'Recalled' in the info column, which is an array. # 1 query = Session.query(MyTable) query = query.filter(MyTable.i ...

Content within the Iframe is in the process of loading, followed by

Exploring the code below: <iframe id="myframe" src="..."></iframe> <script> document.getElementById('myframe').onload = function() { alert('myframe is loaded'); }; </script> Is it a possibility that the ifra ...