Search code examples
javascriptmysqlnode-red

node-red displaying msyql results using the dashboard node


Newbie question: I've started playing with node-red and think it could be a great gateway drug for node.js (and javascript for that matter). But I'm already a bit stuck.

I have a flow which is performing a very simply query against a mysql database. I'm getting the results returned to me, but I have so far not been able to parse those results in any meaningful way. It looks the results are returned as an array, but how can I access and manipulate that array, in a function? Below is the data being passed in from the mysql node:

[
  { "at_time": "2017-03-27T18:33:46.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-27T22:14:02.000Z", "event": "woke_up" },
  { "at_time": "2017-03-27T22:14:12.000Z", "event": "food" },
  { "at_time": "2017-03-28T00:13:42.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T03:50:15.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:33.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:38.000Z", "event": "food" },
  { "at_time": "2017-03-28T06:56:29.000Z", "event": "up_for_day" },
  { "at_time": "2017-03-28T18:08:49.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-28T18:32:48.000Z", "event": "woke_up" }
]

Thanks!


Solution

  • JavaScript arrays have many functions available to help you work with their content. It is too broad a subject to provide a succinct answer without more details on specifically what you want to do.

    As you identify, Node-RED is built using JavaScript and its Function node is no different.

    Assuming your Function is receiving that array as msg.payload, you would use the following syntax to access the various elements:

    var firstElement = msg.payload[0];
    var secondElement = msg.payload[1];
    

    and so on.

    Each element of that array appears to be a JavaScript object - with key/value pairs. To access those values you would use the following syntax:

    var first_at_time = firstElement.at_time;
    var first_event = firstElement.event;
    

    These are fundamental operations with javascript and there are plenty of guides available that will introduce you to them, such as: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays