Manuel Bitto
Manuel Bitto

Reputation: 5253

Best way to maintain only one schema between Mongoose and Joi

I'm using Hapi to develop a web service, with Mongoose as ODM and Joi as validator. I really like Joi's validation and the way it connects with HAPI (I need Joi's description function to display some description in swagger) but I don't want to maintain two schemas, one for Joi and one for mongoose; I would like to define my schema using Joi and then being able to export only the basic schema required by Mongoose. For example:

mySchema.js

module.exports = {
    name : String,
    address: String
}

myValidator.js

module.exports = {
    payload: {
        name: Joi.description('A name').string().required(),
        address: Joi.description('An address').string()
    }
}

myModel.js

const mongoose = require('mongoose'),
    mySchema = require('./mySchema');

var schemaInstance = new mongoose.Schema(mySchema),
    myModel = mongoose.model('myModel', schemaInstance);

myHapiRoute.js

const myValidator = require('./myValidator.js'),
    myController = require('./myController.js');

...

{
    method: 'POST',
    path: '/create',
    config: {
        description: 'create something',
        tags: ['api'],
        handler: myController,
        validate: myValidator
    }
}
...

I would like to avoid the hassle to maintain mySchema.js file generating it exactly from Joi's schema.

Any suggestions on how to do it or any different approaches?

Upvotes: 15

Views: 9308

Answers (1)

Felipe Donda
Felipe Donda

Reputation: 206

For this matter you could use Joigoose to convert your Joi schema to a Mongoose schema as the example below:

const mongoose = require('mongoose')
const joi = require('joi')
const joigoose = require('joigoose')(mongoose)

const joiSchema = joi.object().keys({
  name: joi.description('A name').string().required(),
  address: joi.description('An address').string()
})

const mongooseSchema = new mongoose.Schema(joigoose.convert(joiSchema))

mongose.model('Model', mongooseSchema)

Upvotes: 9

Related Questions