LoopBack:稍后设置必填字段

LoopBack: Setting Required Fields at a Later Time

我遇到过这样一种情况,如果 'type' 值为 'online',我希望 'email' 属性 是必需的。在一般观点中,我有一个字段可能需要或不需要取决于另一个字段值。我将如何解决这种情况?

"properties": {
    "type": {
      "type": "string",
      "required": true
    },
    "email": {
      "type": "string"
      "required": //true or false depending on what 'type' is
    }
  }

将所有可能不需要的字段声明为非必需字段,并使用 operation hook before save 来验证自定义逻辑功能中的字段。

在您的 model.js 文件中,使用您需要的逻辑实现挂钩。例如,如果类型是 'A' 并且需要电子邮件,但请求中提供了 none,则生成错误并调用 next(err)。这样,请求将被拒绝。

MyModel.observe('before create', function(ctx, next) {
    if(ctx.instance){
        data = ctx.instance
    } else {
        data = ctx.data
    {
    if(data.type =='A' && !data.email){
        next(new Error('No email provided !')
    } else {
       next();
    }
});

清理了@overdriver 的代码以使其更易于实施

  MyModel.observe('before save', (ctx, next) => {
    let obj = ctx.instance;

    if(obj.type == 'A' && obj.email == null){
        next(new Error('No email provided !'));
    }
    else {
        next();
    }
  });