根据 JSON 格式的“描述"动态定义 Mongoose 模式 [英] Defining a Mongoose schema on-the-fly from a JSON-formatted 'description'

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

问题描述

我正在制作一个网络应用程序,它允许用户通过首先以客户端形式注册"架构来在我的服务器上创建他们自己的自定义 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 字段中的每个字段定义,并且通过将其映射到实际类型,将其转换为猫鼬模式的有效字段.所以你可以从这样的事情开始:

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天全站免登陆