Aditya Bhatt Aditya Bhatt - 8 months ago 37
Node.js Question

Defining a Mongoose schema on-the-fly from a JSON-formatted 'description'

I'm making a web app which allows users to create their own custom MongoDB collections on my server by first 'registering' the schema in a client-side form.

So the user will create a schema client side - say using a form like this:

So the client-side Js will generate a JSON object of the form, for example:

"collection_name": "person",
"name": "String",
"email": "String",
"id", "Number",

Next, the page will send this object to the server, which should convert the stuff in
to a proper Mongoose Schema and create a collection from it, of collection name

I'm lost - how would I go about doing this? I'm talking about the conversion-to-schema part.


If I understand the goal correctly, you will want loop over each of those field definitions in the data field in the JSON object and convert it to a valid field for a mongoose schema by mapping it to an actual type. So you might start with somethign like this:

var mongoose = require('mongoose')

var typeMappings  =

function makeSchema(jsonSchema){
  var outputSchemaDef = {}
  for(fieldName in{
    var fieldType =[fieldName]
      outputSchemaDef[fieldName] = typeMappings[fieldType]
      console.error("invalid type specified:", fieldType)
  return new mongoose.Schema(outputSchemaDef)

In order to deal with embedded objects and array types, you will probably want to modify this to make it recursive, and descend deeper when it encounters an object of those types, since the fields could be nested together with arbitrary depth/structure.

Hope this helps.