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

Using dynamic classes within a v-for loop

Edited How can I dynamically assign classes to multiple elements within a v-for loop? Since I cannot utilize a computed property due to the presence of v-for, I attempted using a method by passing the index of the element, but that approach did not yield t ...

What is the iPad version of the onmousemove event?

I am currently facing an issue with a website on my iPad. Everything seems to be in order except for the onmousemove method. I am looking for a way to have onmousemove activated when the user swipes their finger across the screen. ...

React Native's state changes dynamically, however, the JSX conditional rendering fails to update the user interface accordingly

Greetings and thank you in advance for your time! I'm currently facing a unique challenge with React where I am struggling to render a specific UI element based on a check function. My goal is to create a multiple selection filter menu, where clickin ...

How can I trigger an Iframe JavaScript function from within my webpage?

I have an Iframe within my page, with the following JavaScript code: function getTotSeats(){ window.WebAppInterface.showToast(document.forms[0].txtSeat_no.value); return document.forms[0].txtSeat_no.value; } I would like to call the above Jav ...

Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem. Your assistance is greatly appreciated, João var inputs = Array.prototype.slice.call(document.querySele ...

JavaScript issue: "No relay configuration found" error specifically occurs in Internet Explorer versions 7 and 8

Encountering issues with loading JavaScript only on specific pages in Internet Explorer. Safari, Firefox, and Chrome render the page correctly. Debugging revealed the following errors: 1) No relay set (used as window.postMessage targetOrigin), cannot send ...

Is there a way to display one of the divs in sequence each time the page is reloaded?

Is there a way to display the divs sequentially when the page is refreshed? For instance, on the initial load, only div 1 should appear, and with each refresh it should cycle through divs 2, 3, 4, and 5 before starting over. Below is an example I'm c ...

Steps for implementing overflow scroll on a div with an unspecified height

The layout I'm working with looks like this: .page { width: 360px; height: 704px; border: 1px solid red; } header { height: 10%; width: 100%; display: flex; align-items: center; justify-content: center; background-color: lightblue; } ...

Leveraging jQuery for handling button functionality and making asynchronous requests

I am relatively new to working with jQuery, and while there are plenty of resources available on how to bind buttons, I find that my current setup is a bit more complex than what's typically covered. My situation involves: -Using Django to populate ...

A guide to gathering a variety of data types for an array in Node.js

As a JavaScript beginner, I am on a mission to enhance my skills by solving online judge problems. However, I have hit a roadblock with a specific issue. The problem requires me to take input from the user in the form of an integer and a string in one go, ...

Tips for blocking submissions when a user tries to input a hyperlink

I have encountered a problem in my journey of learning JS and unfortunately, I couldn't resolve it by myself. Lately, spam has been flooding through the form on my website and all my attempts with jQuery and JS to fix it have failed. As a last resort ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Guide to continuously polling a GET request in JavaScript until the response status is successful

In my JavaScript code, I have a function that utilizes AJAX to send a GET request. The response from the request can be either success, fail, or in process if the job is still running. I want this function to continuously send the GET request every few s ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

Linking various nodes together using the capabilities of the Web Audio API

I am experimenting with audio and trying to achieve a few specific goals: Adjust the overall volume of the audio. Modify the volume and delay of a particular channel (left). This is the code I have been working on: var audioContext = window.AudioContex ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...

Streaming Cassandra result sets to the client using ExpressJS

When attempting to stream the JSON result set returned by Cassandra to the browser, I encountered an issue. Although I was able to get it working by using express-stream and stringifying each row before passing it to `res.pipe()`, I ran into problems when ...

Updating the HTML class with JavaScript

My HTML class has two classes $(document).ready(function() { $(".container").hover(function() { $('.green').addClass('display-on'); }); $(".container").mouseleave(function() { $('.black&apos ...

Gather information from various mongodb collections and consolidate them into a single array using Javascript

Is there a way to retrieve the most recent item from multiple collections and store them in an array based on the collection name and newest item? How can I accomplish this either sequentially or asynchronously? let dat = ["test", "test2"]; ...