Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The correct way to define custom bookshelf Collections with registry plugin
const bookshelf = require('bookshelf')
class Users extends bookshelf.Collection {
get model () {
return User
}
}
class User extends bookshelf.Model {
static collection (...args) {
return new Users(...args)
}
}
bookshelf.collection('Users', Users)
bookshelf.model('User', User)
@fl0w

This comment has been minimized.

Copy link
Owner Author

@fl0w fl0w commented May 6, 2018

const account = await bookshelf.model('Account').forge({ id: 1 }).fetch({ withRelated: 'users' })
account.related('users') instanceof Users // -> true
account.users() instanceof Users // -> true
bookshelf.model('User').collection() instanceof Users // -> true

This'll also allow to define custom logic when collection is eager loaded:

class Users extends bookshelf.Collection {
  initialize (...args) {
    super.initialize(...args)
    this.on('fetching', (collection, attrs, options) => {
      if (options.isEager) {
        // Collection is eager loaded, do something amazing
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.