vintorg vintorg - 3 months ago 34
Node.js Question

How to configure Knex for Bookshelf with Kraken.js

I am trying to integrate Knex (which I used on a previous app that did not use kraken.js), but I need it now for my ORM (bookshelf.js). I came across this post while researching, but I'm still a little fuzzy. This is for a mysql DB.

Where should I create the connection so I can pass it to the bookshelf object for my models?


Just set it as a global object in your onconfig() handler. Something like this:


"databaseConfig": {
  "host": // db host
  "database": // db name
  "user": //db user
  "password": //db pass


var bookshelf = require('bookshelf')(global.db);
module.exports = function Bookshelf() {
  return bookshelf;


var options = {
  onconfig: function(config, next) {
    global.db = require('knex')({
      client: 'mysql',
      connection: config.get('databaseConfig')

    next(null, config);

When you need your bookshelf object to define your models, you can include it and it's ready to go:


   var bs = require('../lib/bs')();

    var Account = bs.Model.extend({
      idAttribute: 'id',
      tableName: 'accounts'

    module.exports = function AccountModel() {
      return Account;

There's other ways to do it, but this is clean and should suffice for what you need.