thinky icon indicating copy to clipboard operation
thinky copied to clipboard

pre save hook is not called on updates

Open ralyodio opened this issue 9 years ago • 8 comments

Tag.pre('save', function(next) {
  this.name = this.name.toLowerCase(); //docs were wrong here, they didn't use `this`
  next();
});

It works when I call Tag.save() but not when I call .update()

var result = yield Tag.get(id).update(data).run();

ralyodio avatar Jun 13 '15 09:06 ralyodio

So the hook save is not called on update for two reasons:

  1. I'll be honest, I think I forgot to add it.
  2. Because when you write:
Tag.get(id).update(data).run()

Thinky partially validates data on the provided fields, but doesn't run the global validation (since you can have validations happening across fields) and directly send that to the server. There's no two round trips (in the normal case).

Anyway, this means that the pre-hook for save is called with a partial document, so the hook was working for update, this would break:

Tag.pre('save', function(next) {
  this.name = this.name.toLowerCase();
  next();
});

var result = yield Tag.get(id).update({foo: "bar}).run();
// The previous line throws with `cannot read toLowerCase of undefined since this.name is undefined.

The solution is probably to create a new hook update rather than re-using the hook for save.

neumino avatar Jun 13 '15 22:06 neumino

+1 for update hooks. It would be a very useful thing to have.

rasapetter avatar Jun 14 '15 16:06 rasapetter

Hum, so this is a bit annoying and tricky to do in the case where the pre-hook is asynchronous.

neumino avatar Jul 18 '15 12:07 neumino

+1

autholykos avatar Feb 03 '16 10:02 autholykos

+1 for update hooks

kevinkleine avatar Jun 02 '16 07:06 kevinkleine

+1 we need update hooks

aikssen avatar Jul 29 '16 02:07 aikssen

+1 any new? I am updating the salt and encrypted password on save, but it's not possible to do it when it's updating.

Is there any solution?

sky10p avatar Jul 31 '19 21:07 sky10p

@neumino Can this please be implemented? or provide a solution to update fields like "lastActive:r.now()" or "updatedAt:r.now()" otherwise I have to stick these Model data updates everywhere.

// Triggers on Model update User.pre('update', function(next) { this.updatedAt = r.now(); next(); });

Thanks for your continued effort towards thinky!

campmedia avatar Jan 26 '20 04:01 campmedia