Defining Mongoose on-the-fly from JSON-formatted "description",

I am creating a web application that allows users to create their own MongoDB collections on my server by first "registering" the scheme in a client form.

Thus, the user will create the client part of the scheme - say, using this form: http://r.github.com/annotationsformatter/

Thus, client-side Js will generate a form JSON object, for example:

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

Then the page will send this object to the server, which should convert the material in data to the correct Mongoose scheme and create from it a collection of the name of the person collection.

I'm lost - how would I do it? I am talking about the conversion to circuit part.

+6
source share
3 answers

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.

+11
source

I wrote a node.js library for this purpose: generate mongoose models from .json configuration .json .

It is called mongoose-gen . It supports all types of mongooses, has hooks for validators, setters, getters and default values.

Hope this helps.

+12
source

I don’t know if he recommended doing it like this, but I only need a JSON file, and then I just remove the name property when creating the request.

 var jsonSchema = require('schema.json'); delete jsonSchema.name; var MySchema = new Schema(jsonSchema); 
0
source

Source: https://habr.com/ru/post/903762/


All Articles