Mask Bookshelf.js models with json-mask
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.


This Bookshelf.js plugin enables you to define masks on your models and serialize to JSON based on its fields using the json-mask API.


npm version node version build status coverage status


Install the package via npm:

$ npm install --save bookshelf-mask


Require and register the bookshelf-mask plugin:

var bookshelf = require('bookshelf')(knex);
var mask = require('bookshelf-mask');


Define masks on your models with masks class property:

var Author = bookshelf.Model.extend({
  posts: {
    return this.hasMany(Post);
  tableName: 'Author'
}, {
  masks: {
    custom: 'id,name'

If you're using ES6 class syntax, define masks as static property:

class Author extends bookshelf.Model {
  get tableName() {
    return 'Author';

  posts() {
    return this.hasMany(Post);

  static masks = {
    custom: 'id,name'

Use the mask method to serialize the registered masks or pass the fields directly:

  .forge({ name: 'foo' })
  .fetch({ withRelated: 'posts' })
  .then(function(model) {
    // => { id: 1, name: 'foo' }
    // => { name: 'foo', posts: [{ title: 'biz', body: 'baz' }, { title: 'qux', body: 'qix' }]}

The mask method can be applied to collections and the same options accepted in toJSON can also be provided.


Contributions are welcome and greatly appreciated, so feel free to fork this repository and submit pull requests.

Setting up

  • Fork and clone the bookshelf-mask repository.
  • Duplicate test/knexfile.js.dist and and update it to your needs.
  • Make sure all the tests pass:
$ npm test


bookshelf-mask enforces linting using ESLint with the Seegno-flavored ESLint config. We recommend you to install an eslint plugin in your editor of choice, although you can run the linter anytime with:

$ eslint src test

Pull Request

Please follow these advices to simplify the pull request workflow:

  • If you add or enhance functionality, an update of usage section should be part of the PR.
  • If your PR fixes a bug you should include tests that at least fail before your code changes and pass after.
  • Keep your branch rebased and fix all conflicts before submitting.
  • Make sure Travis build status is ok.