【问题标题】:How To Store Polygon Coordinates (GeoJSON) as an array into a MongoDB Database Using NodeJS and Mongoose如何使用 NodeJS 和 Mongoose 将多边形坐标 (GeoJSON) 作为数组存储到 MongoDB 数据库中
【发布时间】:2017-01-11 18:12:30
【问题描述】:

我正在尝试使用 Mongoose 将多边形存储到我的 MongoDB 数据库中。我已经尝试了所有替代方案,但不幸的是我无法弄清楚。我找到了一种将坐标存储为字符串而不是 geoJSON 数组(多边形)的方法。
organization 对象的 territory 属性应该是 polygon 并且应该存储在数组中。
我使用POSTMAN 进行测试,下面是我对坐标的POST 请求的截图:

当我提交我的帖子请求时,我收到了这个错误:


以下是对象如何存储在数据库中,作为字符串而不是点数组

我尝试了以下代码的多个版本,我得到了上述响应或另一个说明cast to array failed for value...
请告诉我我做错了什么或如何使它工作。

下面是我的代码。

Organization.js

var mongoose = require('mongoose');  
var organizationSchema = mongoose.Schema({  
name:String,  
address:String,  
point:{type:[Number],index:'2d'},  
territory:{  
  type:{  
    type:String,  
    required:true,  
    enum:['Point','LineString','Polygon'],  
    default:'Point'  
  },  
  coordinates:[mongoose.Schema.Types.Mixed]    
}    
});  
organizationSchema.index({coordinates:'2dsphere'});

API.js

var Organization = require('./models/organization');
var express  = require('express');
var mongoose = require('mongoose');
var apiRoutes = express.Router();
    apiRoutes.route('/organizations')
      .post(function(req,res,next){
          var organization = new Organization();
          var pointData = {
              latitude:req.body.latitude,
              longitude:req.body.longitude
          };
          var loc = req.body.coordinates;

          organization.name = req.body.name;
          organization.address = req.body.address;
          organization.latitude = req.body.latitude;
          organization.longitude = req.body.longitude;
          organization.point = [pointData.longitude,pointData.latitude];
          organization.territory = {
             coordinates: loc,
             type: req.body.type
          };
          //save the new organization and check for errors
          organization.save(function (err, organization) {
            if (err)
                return res.send(err)
            res.json({ 
                message: 'The Organization was successfully created!',
                Organization: organization 
            });
          });
     });

【问题讨论】:

  • 你还需要答案吗?
  • 我仍然这样做。欢迎您的回答

标签: arrays mongodb mongoose geometry geojson


【解决方案1】:

我在github 上创建了一个存储库,以举例说明如何在 NodeJS 驱动的后端中存储多边形和圆坐标。 我可以告诉你哪里出了问题,但这可能无法解决你的问题,而且你会被另一个问题所困扰。 对于初学者
1.你的模式声明是错误的。它应该有一个类型和一个坐标元素。
2. 在排序坐标时,先是经度,再是纬度。文档中提到了这一点

有关更多详细信息,您可以前往 repo 运行代码并自行了解。如果您仍然发现任何问题。请通过 GitHub 或此处告诉我。

【讨论】:

  • 你能在这里发布答案吗?你给的 github 链接不工作
  • 当然可以。给我24小时。
猜你喜欢
  • 2018-04-05
  • 1970-01-01
  • 2012-06-23
  • 2019-03-10
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多