Return rows with nodes and node-mysql

I am discovering Nodejs and the node-mysql module. I have a little problem. Each tutorial that I found explains how to make a choice in the database, but they never return rows, they always register them, which is absolutely useless for my case.

I have an app.js file:

// Get continents app.get("/continents", function(request, result) { console.log("Continents : " + database.findAllContinents()); }); 

And the mysql.js file:

 exports.findAllContinents = function(connection) { var connection = getConnection(); connection.query('select id, code, name from Continent', function (err, rows, fields) { if (err) { console.log("Error in findAllContinents : " + err) } return JSON.stringify(rows); }); closeConnection(connection); }; 

How can I make a function return strings to use in the app.js file? I do not want to create connections in the app.js. I want the DAO layer to be separated. Do you have any ideas?

Also, if someone has an idea of ​​the pros and cons of using node-mysql instead of ORM (sequelize, persistence.js ...)

thanks

+4
source share
1 answer

query() is an asynchronous function from which you cannot return any results. And therefore, any functions that call the asynchronous functions themselves (for example, your findAllContinents ) cannot either.

Instead, you need to pass a callback function (also explained here ) that will be called when the request is executed:

 // app.js app.get("/continents", function(request, response) { database.findAllContinents(function(err, results) { if (err) throw err; // or return an error message, or something else res.send(results); // as a demo, we'll send back the results to the client; // if you pass an object to 'res.send()', it will send // a JSON-response. }); }); // mysql.js exports.findAllContinents = function(cb) { var connection = getConnection(); connection.query('select id, code, name from Continent', function (err, rows, fields) { // close connection first closeConnection(connection); // done: call callback with results cb(err, rows); }); }; 

As for the (non) use of ORM, it really depends on the use case. I would choose ORM (my favorite for MySQL patio ) if my application needs several (complex) models, possibly with associations between them. In addition, the ORM abstraction makes it easier to read the code and, as a rule, allows you to more easily transfer the application to another database.

+14
source

All Articles