简体   繁体   English

环回模型在保存之前删除属性或属性

[英]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 . 到目前为止,我试图在保存之前使用Loopback的操作挂钩捕获实例。

   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. 通过将属性设置为undefined不能确定上面的代码为什么不起作用,但是您可以将其他任何值设置为其他属性。

UPDATE: The code above was actually working. 更新:上面的代码实际上正在工作。 But I have the problem with the instances which already has that attribute I want to remove. 但是我的实例存在问题,该实例已经具有要删除的属性。

In Loopback version 3, 在环回版本3中,

In case of ctx.data 如果是ctx.data

delete ctx.data['propertyToBeRemoved'];

In case of ctx.instance 如果是ctx.instance

ctx.instance.unsetAttribute('propertyToBeRemoved')

This statement prevented the unwanted property in the context of hooks from being saved to database. 该语句阻止了挂钩环境中不需要的属性被保存到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM