Aditya Bhatt Aditya Bhatt - 5 months ago 26
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: http://r.github.com/annotationsformatter/

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

{
"collection_name": "person",
"data":
{
"name": "String",
"email": "String",
"id", "Number",
}
}


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

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

Answer

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  =
{"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)
}

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.

Comments