Mongoosify is a Javascript library to parse a JSON Schema into a Mongoose Schema.
npm install mongoosify --save
Let suppose the JSON object is saved as jschema.json
{
"type":"object",
"properties":{
"address":{
"type":"object",
"properties":{
"street":{"type":"string"},
"house":{"type":"string"},
"city":{"type":"string"}
}
},
"firstName":{"type":"string"},
"lastName":{"type":"string"},
"title":{
"type":"string",
"enum":["Dr","Prof.","Ph.D."]
},
"email":{
"type":"array",
"items":{"type":"string"}
},
"age":{"type": "integer"}
}
}The following code demonstrate how to parse a JSON schema from the jschema.json file into a mongoose schema (I called it mongoosify :D)
var mongoosify = require("mongoosify");
var mongoose = require("mongoose");
var myJsonSchemaFile = require("./jschema.json");
var mySchema= mongoosify(myJsonSchemaFile);
var Schema = mongoose.Schema;
var mongooseSchema = new Schema(mySchema);
//now you are ready to go...$ npm testMongoosify will always try to cast type implicitly if a schema and the data don't have a same type. If a casting is not possible (e.g. "Hallo" can not be cast into a number but "10" can be) and CastError will be throw by Mongoose.
Unit tests for the actual code
- Enable reusability with keywords
$ref,$schemaandid. - Evaluation of the following constraints:
- schema keywords:
additionalPropertiesrequired
- array keywords:
minItemsmaxItemuniqueItems
- numeric types keywords:
minimummaximummultipleOf
- string keyword:
format
- schema keywords:
Want to contributor? Just need a pull request! I look forward to have as contributor on board!