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 ?

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.