Reputation: 1105
I want a suggestion on how to perform nodejs-DB operations
Here are my options
case one : When you have to run more than one query and former one is dependent on the latter
first way
connection.query(Q1, function(error, results, fields) {
if (error) {
throw error;
}
console.log(results[0]);
//call the second query here
connection.query(Q2, function(error, results, fields) {
if (error) {
throw error;
}
console.log(results[0]);
});
});
or
define first query in a function return the result via promise and await function
call the second query in the same way
use both results
like
var res1 = await funcName1(params);
var res2 = await funcName2(params);// params deducted from res1
which one is better?
case two : when we want to call select query more than 1 times
and capture the results in an array
the last one is pretty preplexing, do i have to call the mysql async function in a loop? is it a correct way?
Can you guys redirect me in the correct way?
Upvotes: 0
Views: 109
Reputation: 30675
I would suggest using the second option, or rather a similar approach to the second option. I believe the code is much easier to read and simpler to maintain. You'll also end up with a fraction of the number of lines of code.
It's also worth nothing that many database modules such as mysql2 and mongodb return promises directly, so there's no need to create wrapper functions, that is you won't need to maintain a load of funcName1, funcName2.. etc.
for example using mysql2:
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection({
host: 'localhost',
user: 'some_user',
password: '***',
database: 'test_db'
});
let [users] = await connection.query('select * from users');
let [accounts] = await connection.query('select * from accounts');
console.log( { users, accounts })
If you wish to create promisified wrapper functions for a generic db access proc, have a look at Util.promisify, this allows you to cut down on boilerplate code.
e.g.
const dbQuery = util.promisify(db.query);
Then you can use like
let result = await dbQuery(param1, param2...);
As long as db.query looks something like
db.query(query, callback(err, result))
Also, querying within loops should work very well, for example:
async function testLoopQuery() {
for(let organization of organizationList) {
let [users] = await connection.query('select * from users where org_id = ?', [organization.id]);
}
}
Upvotes: 1