簡體   English   中英

從JSON格式的“描述”中即時定義Mongoose模式

[英]Defining a Mongoose schema on-the-fly from a JSON-formatted 'description'

我正在創建一個Web應用程序,它允許用戶首先在客戶端表單中“注冊”架構,從而在我的服務器上創建自己的自定義MongoDB集合。

因此,用戶將創建一個模式客戶端 - 比如使用這樣的表單: http//r.github.com/annotationsformatter/

因此客戶端Js將生成表單的JSON對象,例如:

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

接下來,頁面將此對象發送到服務器,服務器應將data的內容轉換為正確的Mongoose Schema並從中創建集合名稱person的集合。

我迷路了 - 我怎么會這樣做? 我在談論轉換到架構部分。

我正是為此目的編寫了一個node.js庫:從.json配置文件生成mongoose模型。

它被稱為mongoose-gen 它支持所有mongoose類型,它具有驗證器,setter,getter和默認值的鈎子。

希望能幫助到你。

如果我正確理解了目標,您將需要在JSON對象的data字段中循環遍歷每個字段定義,並通過將其映射到實際類型將其轉換為mongoose模式的有效字段。 所以你可以從這樣的某些東西開始:

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)
}

為了處理嵌入對象和數組類型,您可能希望修改它以使其遞歸,並在遇到這些類型的對象時下降得更深,因為字段可以與任意深度/結構嵌套在一起。

希望這可以幫助。

我不知道是否建議像這樣做,但我只需要我的JSON文件,然后我只需刪除在require期間創建的“name”屬性。

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

var MySchema = new Schema(jsonSchema);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM