Home > Software design >  weird javascript behaviour while computing backend data
weird javascript behaviour while computing backend data

Time:04-29

While filtering data on the backend for some reason the expected response data is wrong but the logs are fine.

basically I have this data inside my mongodb database:

{
  _id: new ObjectId("626a2f00551aa3876e2562eb"),
  username: 'Warren Buffet',
  email: '[email protected]',
  money: 158,
  trades: [
    {
      coin: 'BTC',
      open: 39341.40429922862,
      amount: 500,
      id: '38b6dbf9-8641-46c0-a2ed-6438dad3515c',
      _id: new ObjectId("626a2ff1551aa3876e2562f2")
    },
    {
      coin: 'SOL',
      open: 99.21601863521198,
      amount: 72,
      id: '71e1034e-1466-4d61-b490-22c096c616c6',
      _id: new ObjectId("626a3e833aa72fb27a936256")
    },
    {
      coin: 'VET',
      open: 0.051906156364343044,
      amount: 100,
      id: '0c1d687c-9efc-4e1f-b1c2-edff3416fc41',
      _id: new ObjectId("626a3e913aa72fb27a93625c")
    },
    {
      coin: 'MKR',
      open: 1678.9138538755535,
      amount: 120,
      id: '18c64d96-ac8d-4c4b-b320-b06ce226e845',
      _id: new ObjectId("626a3ea03aa72fb27a936262")
    },
    {
      coin: 'DOT',
      open: 16.923201350318724,
      amount: 50,
      id: '0fd4f53e-335c-4c66-b99c-47ba1898d954',
      _id: new ObjectId("626a3f023aa72fb27a9364e9")
    }
  ],
  __v: 5
}

there are multiple documents like this one.

let users = await User.find();

    const data = users.map((user) => {
      
      const money = user.money.toFixed(2);

      let investedMoney = user.trades.map((value) => value.amount);
      investedMoney = investedMoney.reduce((prev, curr) => prev   curr, 0);
      console.log(investedMoney); //I get the expected value
      return {
        username: user.username,
        money: money   investedMoney, //the actual response data contains only 'money', not 'money   investedMoney'
        trades: user.trades.length,
      };
    });
    res.status(200).json({ success: true, data: data });

this is my code. The point is gathering username, money (both invested and non invested) and number of trades. For some reason my response data contains only the money value, completely ignoring the moneyInvested. The weird thing is that I've tried logging out moneyInvested and I actually get the expected value. Not sure what's wrong here to be honest.

CodePudding user response:

Found it, the money var is a string. Replace

 return {
    username: user.username,
    money: money   investedMoney, //the actual response data contains only 'money', not 'money   investedMoney'
    trades: user.trades.length,
  };

with

 return {
    username: user.username,
    money: Number(money)   investedMoney, 
    trades: user.trades.length,
  };
  • Related