0

I am connecting my application in node.js to postgresql and getting the results and making it into Json. But when I am making a request to the node.js route I am getting the results appended into the variable in which i am storing the db result instead of getting loaded everytime.

The code snippets is like:

function getDBData(request,response,next){
    console.log(request.params);

    var client = new pg.Client(connStr);

        // Connecting to the client
    client.connect(function(err) {
       if (err) { 
         return console.error('could not connect to postgresq',err);
        }      
             console.log('CONNECTION ESTABLISHED');
        })

     // Querying the DB  
      var query = client.query('SELECT * FROM city');
      var i = 0;
      query.on('row', function(row) {

                if(i == 0){
            rowData = rowData + row;
                    i++;    
        }else{
                    rowData = rowData +","+ row;
                    i++;
                }   
      });

          swiftarr= JSON.stringify(rowData);
          //client.end();    
          response.send(200,swiftarr).end();
}

 app.get('/mycity',getDBData)

in the swiftarr variable the results are getting appended instead of getting replaced with every request.

The results i am getting on the browser is like "[object Object],[object Object][object Object],[object Object]"

Instead with every request I should get something like this [object Object],[object Object]


Since in my db i have only two records. For ex. if i make the first request two records are coming into the result variable next time instead of getting replaced it's getting appended and getting four records into the result variables.

I don't know whether i am making any logical error.

anand
  • 1,711
  • 2
  • 24
  • 59
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Ben Fortune Nov 25 '14 at 11:45
  • It's not related to ajax call.. I am able to get the response but my reponse result is getting appended instead of getting replaced with every request...@BenFortune – anand Nov 25 '14 at 11:49
  • It's related due to the nature of your request. It is an asynchronous request and you're trying to return the results before they have been returned. – Ben Fortune Nov 25 '14 at 11:54
  • @BenFortune you are wrong. The data is returned in the callback, so he is not trying to return the results before they have been fetched. – Vitalii Zurian Nov 25 '14 at 11:55
  • @VitaliyZurian It's an asynchronous request... He's calling `response.send().end()` without knowing if `query.on('row')` has actually finished populating the results. – Ben Fortune Nov 25 '14 at 12:05
  • @BenFortune & VitaliyZurian thanx for your effort... at last i got the result and also the concept... – anand Nov 25 '14 at 12:19

2 Answers2

1

Your code is asynchronous, you're calling response.end() before waiting for your results to populate.

function getDBData(request, response, next) {

    var client = new pg.Client(connStr);

    // Connecting to the client
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgresq', err);
        }
        console.log('CONNECTION ESTABLISHED');
    })

    // Querying the DB  
    var query = client.query('SELECT * FROM city');
    var rowData = [];

    query.on('row', function(row) {
        rowData.push(row);
    });

    query.on('end', function(){
        var swiftarr = JSON.stringify(rowData);
        response.send(200, swiftarr).end();
    });
}
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
0

You should either unset your variable by rowData = null somewhere or define it as a local variable in the beginning of the execution with var rowData = {}. Currently you are just assigning it to the global scope.

Try this:

function getDBData(request,response,next){
    console.log(request.params);

    var client = new pg.Client(connStr);

        // Connecting to the client
    client.connect(function(err) {
       if (err) { 
         return console.error('could not connect to postgresq',err);
        }      
             console.log('CONNECTION ESTABLISHED');
        })

     // Querying the DB  
      var query = client.query('SELECT * FROM city');
      var i = 0;
      var rowData = {};
      query.on('row', function(row) {

                if(i == 0){
                    rowData = rowData + row;
                    i++;    
                } else {
                    rowData = rowData +","+ row;
                    i++;
                }   
      });

          swiftarr= JSON.stringify(rowData);
          //client.end();    
          response.send(200,swiftarr).end();
}
Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81