Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi Nested schema

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?

like image 388
Anshul Avatar asked Sep 05 '25 03:09

Anshul


2 Answers

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)
like image 57
Túbal Martín Avatar answered Sep 07 '25 20:09

Túbal Martín


You could use object.keys API

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

var base = joi.object({
    a: joi.string(),
    nestedData: nestedSchema
});
like image 30
Francesco Pezzella Avatar answered Sep 07 '25 19:09

Francesco Pezzella