Array not being passed to query in knex
According to Knex docs on raw parameter binding, we need to add ?
for every element in our array that would be binded to the query:
Since there is no unified syntax for array bindings, instead you need to treat them as multiple values by adding ? directly in your query. http://knexjs.org/#Raw-Bindings
const myArray = [1,2,3]
knex.raw('select * from users where id in (' + myArray.map(_ => '?').join(',') + ')', [...myArray]);
// query will become: select * from users where id in (?, ?, ?) with bindings [1,2,3]
The values show as strings because knex
requires that arrays be passed as arguments within a containing array. From the documentation for raw bindings:
Note that due to ambiguity, arrays must be passed as arguments within a containing array.
knex.raw('select * from users where id in (?)', [1, 2, 3]); // Error: Expected 3 bindings, saw 1 knex.raw('select * from users where id in (?)', [[1, 2, 3]]) Outputs: select * from users where id in (1, 2, 3)
You can fix this by passing the cols
array within an array itself:
if (query.cols) {
var cols = query.cols.map(Number);
console.log(cols)
search.whereIn('collection_id', [cols])
}