Efficiently handling HTTP requests to Postgres yields diverse outcomes

I'm currently working on fetching data from a PostgreSQL database using Node.js with the pg package and Angular.

However, I've encountered an issue where making multiple fast calls to the database results in messed up responses. Some of the data appears to be duplicated or even tripled in consecutive responses.

The code used for the call from Angular is quite simple:

$http({
  url: "/db?table=appointments&type=perDoctor",
  method: "POST"
}).then(...);

On the server-side (using Passport and Express), here's how it's handled:

var pg = require('pg');
var config = {
  host: '***',
  user: '**',
  password: '**',
  database: '**',
  ssl: true
};

var conString = process.env.DATABASE_URL || config;
var client = new pg.Client(conString);
client.connect();
appointments = [];
var queryString = "SELECT * FROM appointments;"
var query = client.query(queryString);
query.on("row", function(row) {
  appointments.push(row);
});
query.on("end", function() {
  client.end();
  res.send(appointments);
});

As you can see from the image below (although the actual number of records in the database is 502), the results are not as expected: enter image description here

Answer №1

After resolving your problem, I have decided to convert my comments into an answer.

It appears that you may need to declare the appointments variable correctly as a local variable. This will prevent any unintended sharing of the variable between different request handlers that may be running simultaneously. If this sharing occurs, one handler might overwrite data from another one.

By the way, if you opt for strict mode in your code, it will promptly highlight these errors for you.

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

Explore numerous databases using mongoosastic

Currently in my Node.js application, I am utilizing Mongoosastic to fetch data from ElasticSearch : Article.search({ "match_all": {} }, function (err, results) { console.log(results.hits.hits); Post.search({ "match_all": {} }, function (err, r ...

Sending a variable to an EJS include

I have a unique footer that is being used in multiple sections of my website. I wanted to set its location as a variable that can be passed when rendering a template. For example: var footerLocation = 'some/location/footer.ejs'; res.render( vi ...

Tips on removing an object array in Node.js

I am working on a basic to-do list application using React.js and Node.js without involving a database. I am able to delete elements one by one from the front end, but I need help with deleting them from the Node backend. Can anyone assist me with this? t ...

Remembering checkboxes labeled as arrays

Below is the code snippet I am working with: router.post('/expenseReport', ensureAuthenticated, async (req, res) => { try { const{ startDate, endDate } = req.body; var expenseArray = []; var count = 0; var ...

WebSocket implementation performance evaluation

Update: I will now narrow down this question to focus on the essential information. Can someone provide a comparison of the performance in MB/s between the two websocket implementations mentioned below? No need for application or hardware specifics, jus ...

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

Streamlining the Compilation of Dependencies for Electron Application Distribution

I am currently exploring the best method to package and distribute various dependencies (such as node modules and client-side scripts/frameworks like Angular) with my Electron App. While the standard approach of npm install module-name --save is effective ...

Ways to utilize Pub / Sub Notifications for Cloud Storage

In order to utilize Pub/Sub Notifications for Cloud Storage, I am working with storage files on Firebase and need to perform various processes. These processes result in additional data being stored in different fields on Firebase. However, there are insta ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

Attempting to establish a basic socket connection utilizing socket.io

Encountering an issue that states: Port error: Could not establish connection. Receiving end does not exist. Struggling to find a solution, can anyone offer assistance? Below is the code snippet: Server (app.js) var app = require('express&apos ...

Issues with Firebase-admin preventing writing to the database are occurring without any error messages being displayed

Issues with Firebase admin writing to the database. The database is instantiated as follows: var db = admin.database(); A reference to the desired table is then set up: var systemsRef = db.ref("systems/"); A function is created to check if a 'sys ...

Is it necessary to include npm as a dependency in the package.json file?

If you mistakenly run npm i npm, it will include npm as a dependency in the package.json file and add entries to the package-lock.json. Is it advisable to roll back this change? Or could there be any valid reason for having npm listed as a dependency in t ...

How can I prevent Heroku from automatically running the script with 'npm start'?

I am currently in the process of developing a server-based application that utilizes automated scripts, also known as "bots," within a cloud environment. I have set up Heroku Scheduler to execute one of these scripts automatically, as illustrated in Figure ...

Unable to retrieve hours from MongoDB date array

Whenever I fetch data from my NodeJS+MongoDB webservice, I am able to retrieve the date format successfully. However, I am facing an issue when trying to extract hours from it. Here is how the date looks in MongoDB: https://i.stack.imgur.com/qxWGL.png I ...

Getting the actual user IP or remote IP address in Node.js and Express.js

Can someone assist me with a dilemma I'm facing? Currently, I have an expressjs application where I need to display the IP of the user accessing it. However, every time I try, it only shows the server's IP instead. I would like to show the actual ...

Sails.js's powerful full text search capability

Can Sails.js and/or Waterline support full text search? While PostgreSQL does support full text search, it appears that the PostgreSQL adaptor for Waterline may not have this feature. Is an efficient full text search achievable with Waterline's cont ...

Exploring JADE within the NodeJS Technology Framework

Currently, I am developing a proof of concept in Node JS, and from my research, the standard tech stack typically consists of Jade (as opposed to HTML), NodeJS, and a database. My query is whether we can substitute HTML 5 for Jade instead. This way, I can ...

Having trouble accessing stored images in node.js/express

After saving some images in the directory myproject/controllers/upload, I included app.use(express.static(__dirname + '/controllers/upload')); in my app.js. However, when trying to access the image directly in the browser using: http://localhost ...

What are the methods for capturing sequential API markings?

Currently, I am in the process of developing an API server that allows users to define their own routes. However, I have encountered a problem when trying to dynamically handle user-defined routes that match specific tokens. I have attempted two different ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...