If I understand the purpose correctly, you will need to loop over each of these field definitions in the data field of the JSON object and convert it to a valid field for the mongoose schema, matching it with the actual type. So you can start with somethign as follows:
var mongoose = require('mongoose') var typeMappings = {"String":String, "Number":Number, "Boolean":Boolean, "ObjectId":mongoose.Schema.ObjectId, //....etc } function makeSchema(jsonSchema){ var outputSchemaDef = {} for(fieldName in jsonSchema.data){ var fieldType = jsonSchema.data[fieldName] if(typeMappings[fieldType]){ outputSchemaDef[fieldName] = typeMappings[fieldType] }else{ console.error("invalid type specified:", fieldType) } } return new mongoose.Schema(outputSchemaDef) }
To deal with inline objects and array types, you probably want to change this to make it recursive, and go deeper when it encounters an object of these types, since the fields can be nested with an arbitrary depth / structure.
Hope this helps.
source share