Upon updating, how to compare a model instance wit

2019-08-09 13:58发布

问题:

I'm using Sails.js v0.10.5, but this probably applies to more general MVC lifecycle logics (Ruby on Rails?).

I have two models, say Foo and Baz, linked with a one-to-one association. Each time that data in a Foo instance changes, some heavy operations must be carried out on a Baz model instance, like the costlyRoutinemethod shown below.

// api/model/Foo.js

module.exports {
  attributes: {
    name: 'string',
    data: 'json',
    baz: {
      model: 'Baz'
    }
  },

  updateBaz: function(criteria,cb) {
    Foo.findOne( criteria, function(err,foo) {
      Baz.findOne( foo.baz, function(err,baz) {
        baz.data = costlyRoutine( foo.data ); // or whatever
        cb();
      });
    });
  }
}

Upon updating an instance of Foo, it therefore makes sense to first test whether data has changed from old object to new. It could be that just name needs to be updated, in which case I'd like to avoid the heavy computation.

When is it best to make that check?

I'm thinking of the beforeUpdate callback, but it will require calling something like Foo.findOne(criteria) to retrieve the current data object. Inefficient? Sub-optimal?

回答1:

The only optimization I could think of:

You could call costlyRoutine iff relevant fields are being updated.

Apart from that, you could try to cache Foo (using some locality of reference caching, like paging). But that depends on your use case.

Perfect optimization would be really like trying to look into the future :D



回答2:

You might save a little by using the afterUpdate callback, which would have the Foo object already loaded so you can save a call.

// api/model/Foo.js

module.exports {
  attributes: {
    ...
  },

  afterUpdate: function(foo,cb) {
    Baz.findOne( foo.baz, function(err,baz) {
      baz.data = costlyRoutine( foo.data ); // or whatever
      cb();
    });
  }
}

Otherwise as myusuf aswered, if you only need to update based on relevant fields, then you can tap into it in the beforeUpdate callback.

Btw, instance functions should be defined inside attributes prop, lifecycle callbacks outside.