Search code examples
node.jspostgresqlexpresspg-promise

Express JS returns null for a query result and values are shown when queried with pgAdmin


I have the following code for querying a list of country names:

router.get('/', function(req, res) {
  console.log("/");
  const query =
    `SELECT DISTINCT name
         FROM countries`;

  db.map(query, [], a => a.json)
    .then(data => {
      res.send({
        data: data,
        status: 200
      });
    })
    .catch(error => {
      console.log(error);
      res.status(500).send('Error occured');
    });
});

In response, I get the response as follows:

{
  "data": [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    ........
  ],
  "status": 200
}

But when I run the same query using pgAdmin, I get the country names instead of 'null'. Can someone help me figure out the issue? I'm a beginner and has no idea on what's going wrong here.

Thanks in advance.


Solution

  • Your query is selecting the field name, but you are mapping the results using a property called json. You should do the following:

    db.map(query, [], a => a.name)