我正在使用mongoose并试图设置一个自定义验证,告诉该属性是否需要(即非空)如果另一个属性值设置为某事.我正在使用以下代码:
thing: {
type: String,
validate: [
function validator(val) {
return this.type === 'other' && val === '';
}, '{PATH} is required'
]}
Run Code Online (Sandbox Code Playgroud)
{"type":"other", "thing":""}失败正确.{"type":"other", "thing": undefined}或{"type":"other", "thing": null}或{"type":"other"}将验证功能永远不会执行,而"无效"的数据被写入到数据库.