-1

I'm using pg-promise to facilitate requests between Express and a Postgres database.

Using pg-promise's any:

db.any('select * from blog')
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.log('ERROR:', error);
  });

There is only one row in the Postgres table, so the query above gets a block of data from Postgres that, when output to the terminal, looks like this:

[ { id: 1,
    date: '2018-12-17',
    title: 'Here is a Title',
    article: "Okay, there's not much here yet.",
    img1: null,
    img2: null,
    img3: null,
    keywords: 'news' } ]

In an effort to break up this data into usable bits that I can then assign to values in Express, I attempted to use JSON.parse() on this data. I really didn't know what to expect from doing this.

db.any('select * from blog')
  .then(function (data) {
    data = JSON.parse(data); // attempting to parse the Postgres data
    console.log(data);
  })

An error occurred:

ERROR: SyntaxError: Unexpected token o in JSON at position 1

I also tried to call on this data as if it were an object.

db.any('select * from blog')
  .then(function (data) {
    console.log(data);
    console.log(data.id); // attempting to get just the id from the data
  })

Which output to the terminal as:

undefined

How can I use this data within a js environment like Express? Not sure if it makes a difference, but I'm trying to use Pug to template everything to the front-end.

rpivovar
  • 3,150
  • 13
  • 41
  • 79

2 Answers2

2

The select query returns array of objects with each element in the array corresponding to a row in the table (blog) in your case and each key in the object corresponding to the table column.

I am not sure why you are trying to JSON-parse it, as JSON expects an object, and it cannot parse arrays.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
Hari Prathap
  • 102
  • 7
  • It doesn't have to be JSON. I just need to be able to get pieces of the data. I could make separate queries for each piece of data, but that doesn't seem right.. – rpivovar Dec 18 '18 at 15:56
  • Thanks for the tip. Seems like this might be related: https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array – rpivovar Dec 18 '18 at 15:59
  • @rpivovar Welcome. I am glad that it helped you. – Hari Prathap Dec 18 '18 at 16:31
0

Try JSON.parse(JSON.stringify(data));