简体   繁体   中英

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.

I have written a node.js library for exactly this purpose: generate mongoose models from .json configuration files.

It's called mongoose-gen . It supports all mongoose types, it has hooks for validators, setters, getters and default values.

Hope it helps.

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.

I don't know if it's recommended to do it like this, but I just requires my JSON file and then I just removes the "name" property create during the require.

var jsonSchema = require('schema.json');
delete jsonSchema.name;

var MySchema = new Schema(jsonSchema);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM