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?
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] .
Sequelize is an ORM that includes some query builder stuff; Knex is just a query builder, not an ORM.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With