Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access knex query results

Using knex with express, how can I access the results of a knex query?

Example:

var bots = []

response = knex.select('id', 'name').from('robots')
  .then(function(robots){
    console.log(robots);
    bots = robots
  });

console.log(bots)

This will log the robots but not not update the bots array, which is empty.

EDIT:

As a synchronous workaround, in an express route, I stuck the express block inside the knex block:

router.get('/robots', function (req, res) {

  response = knex.select('id', 'name').from('robots').then(function(bots){

    res.render('robots/index', {
      page_title: 'All Robots',
      robots: bots
    }); // res.render

  }); // knex.select

}); // router.get

Is this the recommended pattern?

like image 886
s2t2 Avatar asked Mar 20 '16 07:03

s2t2


People also ask

What does a KNEX query return?

Knex returns an array for all queries, even if there is only one row returned. The name of the user can be accessed from user[0] .

Is KNEX an ORM?

Sequelize is an ORM that includes some query builder stuff; Knex is just a query builder, not an ORM.

What is Knexjs?

js (pronounced /kəˈnɛks/) is a "batteries included" SQL query builder for PostgreSQL, CockroachDB, MSSQL, MySQL, MariaDB, SQLite3, Better-SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use.


2 Answers

knex uses Promises. Specifically, it uses http://bluebirdjs.com/docs/getting-started.html. console.log(bots) will not work because it is called right away, while .then( ... ) is only called after the knex query has been successfully called and run.

Your edited, "synchronous workaround" is the correct method to run the Express response, though you do not need to set that query to var response (see my comment on your question for more on that).

like image 58
kuanb Avatar answered Oct 27 '22 18:10

kuanb


I'd suggest using async/await functions. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

router.get('/robots', async function (req, res) {
  const bots = await knex.select('id', 'name').from('robots');
  res.render('robots/index', {
    page_title: 'All Robots',
    robots: bots
  }); // res.render 
}); // router.get
like image 35
Ciul Avatar answered Oct 27 '22 18:10

Ciul