I am new to nodejs trying to read data from mysql using this library. I am using express framework.
here is the code in my router/index.js file
router.get('/', async function(req, res, next) {
console.log(query);
let data = await query();
console.log(data);
res.send();
});
code to read data from db (There is no issue in connecting to db).
const query = async (table, fields ) => {
try {
const results = await pool.query('SELECT * FROM country limit 1');
return results
} catch(err) {
return err;
}
}
The following is getting logged by console.log(data)
<ref *1> Query {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_callback: undefined,
_callSite: Error
at Pool.query (/Users/siva/Projects/api/node_modules/mysql/lib/Pool.js:199:23)
at query (/Users/siva/Projects/api/db/index.js:4:36)
at /Users/siva/Projects/api/routes/index.js:7:20
at Layer.handle [as handle_request] (/Users/siva/Projects/api/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/siva/Projects/api/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/siva/Projects/api/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/siva/Projects/api/node_modules/express/lib/router/layer.js:95:5)
at /Users/siva/Projects/api/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/siva/Projects/api/node_modules/express/lib/router/index.js:335:12)
at next (/Users/siva/Projects/api/node_modules/express/lib/router/index.js:275:10),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular *1], _timeout: null },
sql: 'SELECT * FROM country limit 1',
values: undefined,
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null,
[Symbol(kCapture)]: false
}
Can someone please help me to overcome this issue?
CodePudding user response:
The mysql
library on NPM does not support promises and thus does not work with await
. You would need one of several wrappers that implement promise support for mysql or make your own. A popular module on NPM is a fork named mysql2
(and they are now coordinating with the mysqljs organization to share common code with the mysql
project). With mysql2
you can do:
const mysql = require('mysql2/promise');
Then, you can use async/await
with mysql calls.