user2252941 user2252941 - 1 year ago 53
Node.js Question

Fast http requests to postgres results in different responses

I am trying to fetch data from a postgres database using nodejs with pg package and angular.

When I make (two or more) fast enough calls to database, I get messed results (some doubled, tripled...) for each consecutive response.

The call from angular is the simplest one

url: "/db?table=appointments&type=perDoctor",
method: "POST"

and one the node side (through passport and express)

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);
appointments = [];
var queryString = "SELECT * FROM appointments;"
var query = client.query(queryString);
query.on("row", function(row) {
query.on("end", function() {

and the results are as shown below (the db records are actually 502):
enter image description here

Answer Source

Making my comments into an answer since it solved your issue.

It looks like you may need to properly declare your appointments variable to be a local variable so it is not inadvertently shared between different requests handlers that are in flight at the same time - allowing one request handler to overwrite the data from another.

FYI, if you put your code in strict mode, then it will flag these mistakes for you immediately as an error.