kripod / knex-orm

Knex-based object-relational mapping for JavaScript.
MIT License
61 stars 6 forks source link

Update docs for update action #22

Open DJercic opened 7 years ago

DJercic commented 7 years ago

I think that it's not clear how to update a model if you don't have the properties fetched.

the most common use case is that you get an object with values that you want to update the model with. And the first instinct based on the docs is to do:

const data = {
  id: 1,
  companyId: 2,
  name: 'Olympia Pearson',
  birthDate: new Date('1982-08-20 00:00'),
};
const employee = new Employee(data, false); 
employee.save();

But if you want to update the model with all the properties you have to do:

const employee = new Employee({}, false); 
Object.assign(employee, data);
employee.save();

and for that reason I would add a set method:

/**
   * @param {Object} [props={}] Properties to assign to object
   * @returns {ModelBase} ModelBase
   */
  set(props = {}) {
    return Object.assign(this, props);
  }

So it can be called like this:

new Employee({}, false).set(data).save();

it would be a good thing also to explain in the docs the lifecycle of oldProps, and when they become just props, the concept is clear if you look through the code and tests, but not on a first glance.