I have model with createdOn and lastUpdatedOn fields in my PersitedModel which are basically dates.I am updating this on the after save
operation hook. This is what MyModel.js looks like.
module.exports = function(MyModel) {
MyModel.observe('after save', function(ctx, next) {
if (ctx.instance && ctx.isNewInstance) {
ctx.instance.updateAttribute('createdOn', new Date());
}
if (ctx.instance && !ctx.isNewInstance) {
ctx.instance.updateAttribute('lastUpdatedOn', new Date());
}
next();
});
}
Now the operation hook keeps calling this method.And Causes my app to crash.
<--- Last few GCs --->
441366 ms: Mark-sweep 1279.7 (1410.5) -> 1279.7 (1410.5) MB, 1093.9 / 0.0 ms [allocation failure] [GC in old space requested].
442456 ms: Mark-sweep 1279.7 (1410.5) -> 1279.7 (1410.5) MB, 1090.7 / 0.0 ms [allocation failure] [GC in old space requested].
443606 ms: Mark-sweep 1279.7 (1410.5) -> 1286.6 (1403.5) MB, 1148.8 / 0.0 ms [last resort gc].
444735 ms: Mark-sweep 1286.6 (1403.5) -> 1293.7 (1403.5) MB, 1129.2 / 0.0 ms [last resort gc].
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 00000173CF3CFB49 <JS Object>
If I remove the code for update of lastUpdatedOn then it works fine.So the problem basically that I am facing is the operation hook keeps calling the method.Is there a way to prevent this.Am I doing something wrong.? I want to call this method only once
For your use-case, you should try using a mixin instead of model hooks. Loopback has some documentation on how you can make your own. There's also one that you can use for this on npm: https://www.npmjs.com/package/loopback-ds-timestamp-mixin