We're working on a Node/Express web app with a Postgres database, using the node-postgres package. We followed the instructions in this question, and have our query working written this way:
exports.getByFileNameAndColName = function query(data, cb) {
const values = data.columns.map(function map(item, index) {
return '$' + (index + 2);
});
const params = [];
params.push(data.fileName);
data.columns.forEach(function iterate(element) {
params.push(element);
});
db.query('SELECT * FROM columns ' +
'INNER JOIN files ON columns.files_id = files.fid ' +
'WHERE files.file_name = $1 AND columns.col_name IN (' + values.join(', ') + ')',
params, cb
);
};
data
is an object containing a string fileName
and an array of column names columns
.
We want this query to extract information from our 'columns' and 'files' tables from a dynamic number of columns.
db.query
takes as parameters (query, args, cb)
, where query
is the SQL query, args
is an array of parameters to pass into the query, and cb
is the callback function executed with the database results.
So the code written in this way returns the correct data, but (we think) it's ugly. We've tried different ways of passing the parameters into the query, but this is the only format that has successfully returned data.
Is there a cleaner/simpler way to pass in our parameters? (e.g. any way to pass parameters in a way the node-postgres will accept without having to create an additional array from my array + non-array elements.)
Asking this because:
- perhaps there's a better way to use the node-postgres package/we're using it incorrectly, and
- if this is the correct way to solve this type of issue, then this code supplements the answer in the question referenced above.