Joi Nested schema

不羁的心 提交于 2021-02-08 12:16:46

问题


I am trying to create nested schema in joi and it is throwing error

[Error: Object schema cannot be a joi schema]

var nestedSchema = joi.object({
    b: joi.number()
});

var base = joi.object({
    a: joi.string(),
    nestedData:joi.object(nestedSchema)
});

How should i define nested schema in joi?


回答1:


You could use object.keys API

var nestedSchema = joi.object().keys({
    b: joi.number()
});

var base = joi.object({
    a: joi.string(),
    nestedData: nestedSchema
});



回答2:


Although Francesco's answer works, there's no need to use object.keys(). The error the question creator was doing is to pass a schema as a parameter to joi.object().

So, creating nested schemas is as simple as assigning a schema to a key belonging to another schema.

const schemaA = Joi.string()
const schemaB = Joi.object({ keyB1: schemaA, keyB2: Joi.number() })
const schemaC = Joi.object({
  keyC1: Joi.string(),
  keyC2: schemaB  
})

Joi.validate({ keyC1: 'joi', keyC2: { keyB1: 'rocks!', keyB2: 3 } }, schemaC)



回答3:


just a tip based on Francesco's accepted answer:

if you need "nestedData" to be required -> "nestedData: nestedSchema.required()" in "base" will not work, you need to set it directly on "nestedSchema" just like any other parameter

    var nestedSchema = joi.object().keys({
        b: joi.number()
    })
    .required();

    var base = joi.object({
        a: joi.string(),
        nestedData: nestedSchema
    });


来源:https://stackoverflow.com/questions/36739427/joi-nested-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!