0

I'm using a npm package (tcmb-doviz-kuru) to get the currency data from api and I'm trying to insert my database. Hovewer i couldnt map the data to insert the values. Here is my code:

var tcmbDovizKuru = require('tcmb-doviz-kuru');
var pg = require('pg');


function cb(error, data) {
    if (error) {
        console.log('error', error)
    }

    insertToDatabase(data);
}

function insertToDatabase(data){
    var pgClient = new pg.Client(connectionString);
    pgClient.connect();

  const text = 'INSERT INTO currency.kur("date", forexBuying, forexSelling, banknoteBuying, banknoteSelling, unit, isim, currencyCode)VALUES(CURRENT_TIMESTAMP,$1,$2,$3,$4,$5,$6,$7)'
  const values = data['tarihDate']['currency'];
  pgClient.query( text, values).then(res => {
    console.log("inserted")
  })
  .catch(e => console.error("error"))

tcmbDovizKuru(cb);
}

and an example of the data from api (data['tarihDate']['currency']):

 {
    attributes: { crossOrder: '0', kod: 'USD', currencyCode: 'USD' },
    unit: 1,
    isim: 'ABD DOLARI',
    currencyName: 'US DOLLAR',
    forexBuying: 8.2981,
    forexSelling: 8.313,
    banknoteBuying: 8.2922,
    banknoteSelling: 8.3255,
    crossRateUSD: null,
    crossRateOther: null
  },
  {
    attributes: { crossOrder: '1', kod: 'AUD', currencyCode: 'AUD' },
    unit: 1,
    isim: 'AVUSTRALYA DOLARI',
    currencyName: 'AUSTRALIAN DOLLAR',
    forexBuying: 6.1339,
    forexSelling: 6.1739,
    banknoteBuying: 6.1057,
    banknoteSelling: 6.211,
    crossRateUSD: 1.3496,
    crossRateOther: null
  }
  
  ]

How can i insert the values each ?

msanli224
  • 41
  • 1
  • 9

1 Answers1

1

The data you are inserting is an object, but the $1 $2.. you are using expects an array.

See What does the dollar sign ('$') mean when in the string to .query?

So you would need to map the object from each of the entries of "data['tarihDate']['currency']"

To insert for the US DATA from your example data

const usdInfo = data['tarihDate']['currency'][0];
const valuesArray = [usdInfo.forexBuying, usdInfo.forexSelling, banknoteBuying, banknoteSelling, unit, isim, currencyCode];

pgClient.query( text, valuesArray ).then(res => {
    console.log("inserted", res)
  })
  .catch(e => console.error("error", e))
Dries Meerman
  • 96
  • 1
  • 6