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?
Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
You can also define MongoDB indexes using schema type options. index : boolean, whether to define an index on this property. unique : boolean, whether to define a unique index on this property. sparse : boolean, whether to define a sparse index on this property.
Mongoose does not natively support long and double datatypes for example, although MongoDB does. However, Mongoose can be extended using plugins to support these other types.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With