LoopBack:稍后设置必需的字段

如果“types”值为“在线”,我遇到了需要“电子邮件”属性的场景。 在一个通用的观点,我有一个字段,可能需要或不依赖于另一个字段的值。 我将如何去解决这个情况?

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

将所有可能不需要的字段声明为非必需字段,并before save使用操作挂钩来validation自定义逻辑的函数中的字段。

在你的model.js文件中,用你需要的逻辑实现钩子。 例如,如果types是'A',并且需要一个电子邮件,但是请求中没有提供,请生成一个错误,然后再调用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(); } });