0

So, I currently work on my first node.js project where I created an api. I would like to create one endpoint, where i would like to give 3 parameters in GET request method: "base" , "target" and "amount", and after retrieving data from mongoDb and apropriate calculations I would like the response to return the given amount given in target currency! The problem is that to access the ratios I get undefined!

my code for this endpoint is:

router.get('/convert', async(req,res)=>{

    let base = req.body.base;
    let target = req.body.target;
    let amount = req.body.amount;


    const getRatios = await Ratios.findOne({base: base});
    if(!getRatios) return res.status(400).send('No such a currency found');

    try{            
        res.send(getRatios.ratios.target);        
    }

    catch(err){

        console.log('something bad happened');
        console.log(getRatios.ratios);
    }

})

The only way to reach the values of the stored ratios is in console after I hard code the desired "target" i would like to access! eg console.log(getRatios.ratios.target) returns undefined but console.log(getRatios.ratios.AUD) returns the rate for AUD

This only works in console, but when I try to get a response : res.send(getRatios.ratios.target) or res.send(getRatios.ratios.AUD) returns nothing!

the res.send(getRatios.ratios) works fine and returns:

{
    "EUR": 0.82110323,
    "AUD": 1.2923873,
    "JPY": 109.49154,
    "USD": 1,
    "CHF": 0.89690769
}

however i would like to get access the object's values!

  • Please console log getRatios and send here – Mohak Gupta Jun 09 '21 at 12:54
  • This is the console.log(getRatios) return { ratios: { EUR: 0.82110323, AUD: 1.2923873, JPY: 109.49154, USD: 1, CHF: 0.89690769 }, _id: 60bfb0508ea40238bca9cdac, base: 'USD', date: 2021-06-08T18:00:48.700Z, __v: 0 } – Georgios Papoutzas Jun 09 '21 at 13:01
  • Hi Georgios! What's the type of the getRatios.ratio? (do console.log(typeof getRatios.ratio)) If it's a string, you might need to parse that into an object first JSON.parse(getRatios.ratios) Also, you're saying that getRatios.AUD returns the rate for AUD, so why not just return that instead of getRatios.ratios.AUD? – Amats Jun 09 '21 at 13:03
  • So how will you get getRatios.ratios.target? – Mohak Gupta Jun 09 '21 at 13:03
  • The type of getRatios.ratios in console is Object! I made an edit, in my question i get the rate only in console when I try console.log(getRatios.ratios.AUD) which is not what I 'm trying to do! I would like the req.body.target to be the key in the getRatios.ratios object and i would to get the value!! Thank you for the responses ! – Georgios Papoutzas Jun 09 '21 at 13:13

0 Answers0