Mark Ryan Orosa
Mark Ryan Orosa

Reputation: 867

Loopback Model Remove attribute or Property before save

I have been trying to wrap around my head with this for some time now.

I want to remove a certain attribute or property of a model before saving.

So far I am trying to catch the instance using Loopback's operational hook before save.

   MyModel.observe('before save', function(ctx, next){

      if (ctx.instance) {
         ctx.instance.removeProperty = undefined; 
      } else {
         ctx.data.removeProperty = undefined;    
      }

      next();

   });

Not sure why the above code is not working, by setting the attribute as undefined but you can set any other value to other properties.

UPDATE: The code above was actually working. But I have the problem with the instances which already has that attribute I want to remove.

Upvotes: 0

Views: 2150

Answers (1)

20B2
20B2

Reputation: 2141

In Loopback version 3,

In case of ctx.data

delete ctx.data['propertyToBeRemoved'];

In case of ctx.instance

ctx.instance.unsetAttribute('propertyToBeRemoved')

This statement prevented the unwanted property in the context of hooks from being saved to database.

Upvotes: 2

Related Questions