验证 Keystone.js 中相互依赖的字段

Validating fields that depend on each other in Keystone.js

我正在尝试在保存项目时进行验证。这是我的精简模型:

Sample.add({
    isPublished: { type: Types.Boolean, default: false },
    thumbnailImage: { type: Types.CloudinaryImage, folder: 'samples/thumbnails' },
});

Sample.schema.pre('validate', function(next) {
    if (this.isPublished && !(_.isEmpty(this.thumbnailImage.image))) {
        next('Thumbnail Image is required when publishing a sample');
    }
    else {
        next();
    }
});

如果 Sample 模型将 isPublished 设置为 true 但尚未设置 thumbnailImage,我想提出错误。当我 console.log() 值时,我分别看到 truefalse,但 Keystone Admin 中没有出现验证错误。

我查看了 Github 上的 Keystone 示例应用程序,Mongoose 文档有很多示例,但我还没有看到任何处理多个文档路径的示例。

位于 mongoose custom validation using 2 fields 的示例(目前有 12 个赞成票)也不适合我。

我做错了什么?我正在使用猫鼬 3.8.35。

您不应该 ! 否定验证条件的第二部分,因为您当前在 not 为空时标记验证错误。

所以改成:

Sample.schema.pre('validate', function(next) {
    if (this.isPublished && _.isEmpty(this.thumbnailImage.image)) {
        next(Error('Thumbnail Image is required when publishing a sample'));
    }
    else {
        next();
    }
});

请注意,在调用 next 报告验证失败时,您还需要将错误字符串包装在 Error 对象中。