Bookshelf: Correct way to strip/ignore unused attributes when saving a model object?

Created on 15 Jun 2016  路  3Comments  路  Source: bookshelf/bookshelf

Sorry if this is not the right place for questions, but I tried posting on stackoverflow but haven't gotten a bite.

I am sending angular model objects to bookshelf to save, but it may carry extraneous attributes that aren't in the database. When I save, bookshelf will try to save all attributes and say it can't find these extra attributes.

What is the recommended way to handle this? I'm sure I can set out an array of whitelisted attributes, and strip the object manually. Or I could even automatically get the whitelisted columns with a

getColumns: function(){
        return knex(this.tableName).columnInfo()
    },

Is there a better way? Does knex/ bookshelf cache the schema somewhere so I don't have to make an extra query?

feature

Most helpful comment

@vellotis I just wrote a quick plugin to do this task. It didn't feel right to rewrite the whitelist for attributes when the info is all there.

https://github.com/1mike12/bookshelf-strip-save
@rhys-vdw can you add this to the plugins page too?

All 3 comments

I have thought about using columnInfo for that as well. There isn't a common way currently. You could solve it with a plugin. There are parse and format methods that you could override (and call super internally).

Look #1101 for some example.

I'd probably just override set and have it read a whitelist from the model.

const MyModel = WhitelistModel.extend({
  attributes: ['this', 'that', 'the_other'],
  // ...
});

You'll need to make WhitelistModel.

@vellotis I just wrote a quick plugin to do this task. It didn't feel right to rewrite the whitelist for attributes when the info is all there.

https://github.com/1mike12/bookshelf-strip-save
@rhys-vdw can you add this to the plugins page too?

Was this page helpful?
0 / 5 - 0 ratings