Get count result with knex.js / bookshelf.js

bookshelf.js, knex.js

Solution

All the results from knex.js are arrays. A query could be successful and simply return 0 results.

Also, you can alias the column directly in the column name (or `count()` call). Like this:

  bookshelf.knex('hosts').count('id as CNT').then(function(total) {
    res.send({
      meta: {
        total: total[0].CNT
      }
    });
  });

Still need to get the first element, but you can reference the column as a normal JSON property.

Problem

I'm trying to perform a simple count with knex (since it seems to not be supported by bookshelf yet). The following code is working: ``` bookshelf.knex('hosts').count('id').then(function(total) { res.send({ meta: { total: total[0]['count(`id`)'] } }); }); ``` It just seems odd to me that I have to do `total[0]['count('id')']` to get the actual result. Am I doing things right here? Thanks!

Original source

Related problems