I am trying to use then() to chain my create table and insertion of rows.
The table is created but no insertion happens (no error is caught).
Can someone tell me where I am wrong?
Thanks
MN
var Promise = require('bluebird');
var Knex = require('knex');
Knex.knex = Knex.initialize({
client: 'pg',
connection: {
…
},
debug: true
});
var knex = require('knex').knex;
knex.schema.createTable('department', function(table) {
table.increments('department_id').primary().notNullable();
table.string('department_name', 80).unique().notNullable();
table.string('building_name', 40);
}).then (function() {
console.log('department table has been created');
knex('department').insert(
[{department_name:'Nano Technology', building_name:'block-A'},
{department_name:'Mechanical Engineering', building_name:'block-C'}],
'department_id'
);
}).then(function() {
console.log('departments inserted');
}).catch(function(e) {
console.log(e);
});
You have to either return
your knex
insert statement, or add handlers to it (by using then
or catch
/ caught
), else you are just creating a builder
instance but are not actually executing the query. When you call methods like insert
, select
, from
etc. - basically every method on the query builder - it will only modify its internal state, but not actually execute the query. That will only happen when you add one or more handlers to the instance using then
, catch
/caught
, lastly
/finally
,tap
or exec
, because this will then create the actual Promise
, which sends the query to the database client.
Knex and Bookshelf are great. Thanks a lot
On 16 Jan 2014, at 13:17, Johannes Lumpe [email protected] wrote:
You have to either return your knex insert statement, or add handlers to it (by using then or catch/ caught), else you are just creating a builder instance but are not actually executing the query. When you call methods like insert, select, frometc. - basically every method on the query builder - it will only modify its internal state, but not actually execute the query. That will only happen when you add one or more handlers to the instance using then, catch/caught, lastly/finally,tap or exec, because this will then create the actual Promise, which sends the query to the database client.
—
Reply to this email directly or view it on GitHub.
You're welcome!
Most helpful comment
You have to either
return
yourknex
insert statement, or add handlers to it (by usingthen
orcatch
/caught
), else you are just creating abuilder
instance but are not actually executing the query. When you call methods likeinsert
,select
,from
etc. - basically every method on the query builder - it will only modify its internal state, but not actually execute the query. That will only happen when you add one or more handlers to the instance usingthen
,catch
/caught
,lastly
/finally
,tap
orexec
, because this will then create the actualPromise
, which sends the query to the database client.