0

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.

1 Answer 1

3

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;
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @xShirase, how can I pass these array on the variable as a result?
As you can see in my code sample, I wrote 'return records' at the end of the function. I need to use those function in other methods and when I call that function, it returns undefined value. I wanna know to use the function returning JSON object. Thanks
Yes, need to use callback to use the query result, now I can use the sql query result in my process. Thank you! However, is there any way to store the SQL result into a variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.