从JSON格式的“描述”中即时定义Mongoose模式 [英] Defining a Mongoose schema on-the-fly from a JSON-formatted 'description'

查看:235
本文介绍了从JSON格式的“描述”中即时定义Mongoose模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Web应用程序,允许用户在我的服务器上创建自己的自定义MongoDB集合,方法是首先以客户端形式注册架构。

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.

因此用户将创建一个模式客户端 - 比如使用这样的表单: http://r.github.com/annotationsformatter/

So the user will create a schema client side - say using a form like this: http://r.github.com/annotationsformatter/

因此客户端Js将生成表单的JSON对象,例如:

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",
    }
}

接下来,页面会将此对象发送到服务器,服务器应将 data 中的内容转换为适当的Mongoose Schema并且从中创建一个集合,集合名称 person

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.

推荐答案

如果我正确理解目标,你会想要循环JSON对象中 data 字段中的每个字段定义,并通过将其映射到实际类型将其转换为mongoose模式的有效字段。所以你可以从这样的开头开始:

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.

希望这会有所帮助。

这篇关于从JSON格式的“描述”中即时定义Mongoose模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆