【问题标题】:Using Joi schema to get a json object with fields specified in the schema使用 Joi 模式获取具有模式中指定字段的 json 对象
【发布时间】:2020-10-20 01:03:06
【问题描述】:

我不确定以前是否有人问过此类问题,但我找不到与此相关的任何内容。在我当前的项目中,我们使用 Joi 模式来执行验证。我喜欢定义自定义模式并使用该模式对传入对象运行验证的能力。我有一个任务需要过滤掉对象属性。类似于_.pick 的东西,但属性很复杂并且处理嵌套的对象和数组。我们已经设计了一个 joi 模式来执行验证,但我正在考虑使用它来获取对象的特定属性,例如使用该模式过滤对象数据。像这样的:

const Joi = require('joi');
const val = {
  a: 'test-val1',
  b: 'test-val2'
}
const schema = Joi.object({
   a: Joi.string()
});
// now the below result have the object with both `a` and `b`
// properties but I want joi to strip the `b` property from the object
const result = schema.validate(value, { allowUnknown: true });

Joi 的文档没有提到这样的事情。我遇到了this(ajv) 库,它确实可以满足我的需求,但我想确定使用Joi 是否无法实现这一点。提前致谢。

【问题讨论】:

  • 从文档中,您不必添加 removeAdditional 标志来删除 joi 架构未指定的属性吗?
  • @KevinFriedheim 那是为了ajv 库而不是 Joi。我想知道 Joi 是否提供类似的东西。

标签: node.js joi


【解决方案1】:

Joi 提供stripUnkown 属性,可用于仅获取架构中定义的字段。

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2017-07-06
    • 2015-10-23
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多