如何从JSON创建Mongoose模式

时间:2016-09-07 05:51:52

标签: java node.js mongodb mongoose-schema

我是mongodb,nodejs和mongooseJS的新手。最近,我一直在尝试为我的JSON创建一个mongoose模式。

{
  "endpoints":["a","z"],
  "poi":[{
  "location_name": "a",
  "latitude": " 10.1075702",
  "longitude": "76.345662",
  "distance" : "0.0"
}, {
  "location_name": "b",
  "latitude": "10.110199",
  "longitude": "76.3489361",
  "distance" : "2.0"
}, {
  "location_name": "c",
  "latitude": "10.1197471",
  "longitude": "76.342873",
   "distance" : "3.1"
}, {
  "location_name": "d",
  "latitude": "10.1254479",
  "longitude": "76.3332626",
   "distance" : "4.4"
}, {
  "location_name": "e",
  "latitude": "10.1443277",
  "longitude": "76.2566017",
  "distance" : "13.9"
}, {
  "location_name": "f",
  "latitude": "10.1487145",
  "longitude": "76.2441114",
   "distance" : "15"
}, {
  "location_name": "z",
  "latitude": "10.145578",
  "longitude": "76.2317077",
  "distance" : "16.9"
}]
}

这是我的JSON文件。我尝试使用https://github.com/nijikokun/generate-schema中的generate-schema,它给了我以下输出

 { 
endpoints:[ 'String' ], 
poi: [ 'String' ]
 }

我使用了这个,当我使用chrome webstore中的Postman测试它时,我无法使用get请求从数据库中检索完整的JSON。我都没能成功运行发布请求。

最近我尝试使用JSON模式而不是使用

的mongoose模式
mongoose.Schema("JSON Schema')

当我尝试使用JSON Schema时,我能够使用GET请求从mongodb集合中检索数据,但我无法使用JSON模式正确地发布数据

我还在考虑删除nodejs并重新开发java和mongodb中的webservice。如果我尝试使用Java Web服务与mongodb进行交互,是否会影响我的Web应用程序的性能?

1 个答案:

答案 0 :(得分:3)

您可以使用Generate Schemas模块执行此任务。

var jsonObject={
var GenerateSchema = require('generate-schema')
var schema = GenerateSchema.json('Product',jsonObject);

console.log(JSON.stringify(schema))

由于您有两个主要属性,因此endpoints 和其他poi

这是JSON对象的输出模式

    {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Product",
  "type": "object",
  "properties": {
    "endpoints": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "poi": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "location_name": {
            "type": "string"
          },
          "latitude": {
            "type": "string"
          },
          "longitude": {
            "type": "string"
          },
          "distance": {
            "type": "string"
          }
        }
      }
    }
  }
}
  

建议:您将收到一些不需要的字段,您必须对其进行修改。所以我认为你应该根据你的对象创建自定义模式,这对你来说更好

您还可以获得其他参考文献here