0

this function lives in an index.js and is executed with node. The mysql queries are working perfectly fine but when I want to add a "count" to an object from the first result, i just get the following error message:

TypeError: Cannot set property 'count' of undefined

The Problem should be in

result[i].count = innerResult[0].count;

The array of objects looks like this:

[
  RowDataPacket { name: 'Jane Doe', id: 1 },
  ...
]

And finally the code:

var msg = someInt;
con.query("SELECT `candidates`.`name`, `candidatures`.`id` FROM `elections` INNER JOIN `candidatures` ON `elections`.`position` = `candidatures`.`position` INNER JOIN `candidates` ON `candidatures`.`candidate` = `candidates`.`id` WHERE `elections`.`id` = '" + msg + "'", function (err, result, fields) {
   if (err) throw err;
   for(var i = 0; i < result.length ; i++){
         con.query("SELECT COUNT(*) as `count` FROM `votes` WHERE `candidature` = '" + result[i].id + "'", function (innerErr, innerResult, innerFields) {
         if (innerErr) throw innerErr;
         result[i].count = innerResult[0].count;
      });
   }

Does the 2nd query overwrite the "result" even though the 2nd result is named different?

ntedeski
  • 3
  • 2
  • The problem isn't `result`, the problem is `i`. :-) See the linked question for details, but basically, change `var i` to `let i` so that each of those inner callbacks gets its *own* copy of `i`, and it should fix it. – T.J. Crowder Apr 17 '20 at 09:55
  • Thx for the fast answer! That indeed solved the problem. But I still can't set the `result.count` to the `innerResult.count`... – ntedeski Apr 17 '20 at 10:18
  • I wouldn't be surprised if the result objects are frozen in some way so you can't modify them. But note that there's no reason for those inner queries, do the count in your main query: https://pastebin.com/5K37VN7j Also, [**don't** use string concatenation for query parameters](http://bobby-tables.com/)! Use parameterized queries! – T.J. Crowder Apr 17 '20 at 10:28

0 Answers0