jun_mich0327
jun_mich0327

Reputation: 28

How can I pass mysql result in object using node js?

Can anyone knows how can I pass MySQL result to a JSON object using NodeJS?

// my code
var mysql = require('mysql');
var records = {};

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: ''
});

connection.query('USE MyDB');

function getRecords() {
  connection.query("select * from records where id = ?", id, function(err, result) {
    if (err) {
        return done(err);
    }

    records = result;
    return records;
  });
}

From these code, I want to use the return records in other operations in my project. Can anyone help me to pass MySQL result to JSON object so I can use the data outside the function?

Thank you.

Upvotes: 0

Views: 7843

Answers (1)

xShirase
xShirase

Reputation: 12399

It is already an object (more precisely an array of objects).

Let's say your table structure is : 'field1, field2, field3'

Your result object will look like :

[
  { //that's result[0], and contains the values of your first result row
    field1 : row0value1,
    field2 : row0value2,
    field3 : row0value3
  },
  { //then result[1], contains the next row, etc...
    field1 : row1value1,
    field2 : row1value2,
    field3 : row1value3  
  },
   ...
]

So you can access result as a normal array, and each field as a property of result[i]

Then, you need to know that as everything else in Node, the query will be ran asynchronously. Therefore, you can use a callback to get your value.

Add a callback to your function :

function getRecords(cb) {
  connection.query("select * from records where id = ?", id, function(err, result) {
    if (err) throw(err); 
    cb(result);
  });
}

Then, when you need the result, you can use :

getRecords(function(res){
  records = res;
});

Upvotes: 3

Related Questions