bookshelf: set attributes is not updated to database while calling save with patch option

hi all, I found that there is weird issue on save & set and the version of bookshelf.js is 0.10.3

// js code
const model = await Model.forge({ id: 5 }).fetch();
model.set('attr_a', 'some value');
await model.save({ attr_b: 'some value' }, { patch: true });

above operations only update attr_b to database.

In other ORM such as ruby’s ActiveRecord, it will update both attr_a & attr_b

// ruby code
model = Model.find(5);
model.attr_a = 'some value';
model.attr_b = 'some value';
model.save!

Does it make sense that changed attributes should be updated to database no matter what these attributes are changed by set or save method ?

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Comments: 20 (10 by maintainers)

Most upvoted comments

patch: true is really handy to avoid race condition if you have model updated in few places at the same time (happens for user entity pretty often) you can get some property overridden End up with my own attempt of implementing save fuctionality:

async saveModel(attributes?: Partial<CustomUserModelAttributes>, options?: SaveOptions) {
    if (options) {
        return super.save(attributes, options);
    }

    if (attributes) {
        this.set(attributes);
    }

    if (this.hasChanged()) {
        await super.save(this.changed, { patch: true });
        // dirty hack
        if (attributes) {
            Object.keys(attributes).forEach(key => {
                (this as any)._previousAttributes[key] = attributes[key];
            });
        }
    }
}

The problem is if you call set then save with patch: true and check _previousAttributes you’ll see old value, so all consequence call of mine saveModel method fails. Maybe this can be fixed on library level