loopback icon indicating copy to clipboard operation
loopback copied to clipboard

Inconsistency modifing an attribute in a beforeSave hook

Open andreribeirocoelho opened this issue 12 years ago • 6 comments

I'd like to modify a model attribute in a beforeSave hook. How would I do this?

Something like this:

MyModel.beforeSave = function(next, data) {
    // change modified date attribute received here to another value
};

First, a tried using "this":

MyModel.beforeSave = function(next, data) {
    this.modified = "my new value";
};

This only works for POSTing an instance if I change this.__data.modifed also like this:

MyModel.beforeSave = function(next, data) {
    this.modified = "my new value";
    this.__data.modified = "my new value";
};

But when I'm PUTing something this solution does not work.

In order to work with PUT I need to change "data" attribute:

MyModel.beforeSave = function(next, data) {
    data.modified = "my new value";
};

In order to have a consistency attribution for both cases (POST and PUT) I tried to use "data.modified".

This approach only works if I do this:

MyModel.beforeSave = function(next, data) {
    data.modified = "my new value";

    if (data.__data) { // check if is a POST
        data.__data.modified = "my new value";
    }
};

This is pretty confusing because I do not have a consistent way of change the instance and when I'm PUTing something my instance does not have __data attribute.

To be honest I would rather just change the instance and need not change the __data attribute.

andreribeirocoelho avatar Jul 07 '14 21:07 andreribeirocoelho

Is modified in the properties of your model definition?

raymondfeng avatar Jul 07 '14 21:07 raymondfeng

No, it is dynamically created

andreribeirocoelho avatar Jul 07 '14 21:07 andreribeirocoelho

Can you try to make it part of your model definition? I assume that will work for this.modified = new Date() in both cases.

raymondfeng avatar Jul 07 '14 21:07 raymondfeng

It's a schemaless model.

andreribeirocoelho avatar Jul 07 '14 21:07 andreribeirocoelho

@raymondfeng but I suppose that it should work for schemaless models too.

andreribeirocoelho avatar Jul 09 '14 16:07 andreribeirocoelho

We are moving away from beforeSave/afterSave hooks in favour of Operation hooks and Per-method hooks.

Please upgrade your project to use the new before save hook and open a new GH issue if you run into any problem.

MyModel.observe('before save', function(ctx, next) {
  if (ctx.instance) {
    ctx.instance.modified = new Date();
  } else {
    ctx.data.modified = new Date();
  }
  next();
});

bajtos avatar Feb 03 '15 15:02 bajtos