Search code examples
javascriptnode.jsknex.js

Array not being passed to query in knex


I am passing an array of ids from a get query to a knex whereIn function but they are going missing.

if(query.cols){
  var cols = query.cols.map(Number);
  console.log(cols)
  search.whereIn('collection_id', cols)
}

I am mapping them to Integers for the query. The console log is...

[ 77, 66 ]

But the debug shows the query as...

...and "collection_id" in (?, ?) 

What have I missed?


Solution

  • Edit:
    This solution is for a previous version of Knex (v0.12.1)

    The current documentation for raw bindings can be found here: https://knexjs.org/guide/raw.html#raw-parameter-binding

    Old:
    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])
    }