Inconsistency modifing an attribute in a beforeSave hook
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.
Is modified in the properties of your model definition?
No, it is dynamically created
Can you try to make it part of your model definition? I assume that will work for this.modified = new Date() in both cases.
It's a schemaless model.
@raymondfeng but I suppose that it should work for schemaless models too.
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();
});