Naveen George Thoppan
Naveen George Thoppan

Reputation: 571

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.

Upvotes: 2

Views: 1174

Answers (1)

Stefano Dalpiaz
Stefano Dalpiaz

Reputation: 1673

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)

Upvotes: 2

Related Questions