MongoDB的geoJson坐标Mongoose模式

10

我试图为geojson创建一个模式,但在坐标语法方面遇到了一些问题。

这是我的当前代码:

var DataSchema = new Schema({
  properties: {
    title:       { type: String, required: true },
    description: { type: String, required: true },
    date:        { type:Date, default:Date.now }
  },
  geometry: {
       coordinates: []
  }
});

我尝试使用[](空数组),它创建了''[Number,Number],但是它不起作用。

我的问题是:我该如何构建我的模式,以便结果会得到

coordinates: [ 3.43434343, 5.543434343 ]

没有引号,这可行吗?

Express Route

   app.post('/mountain_rescue',  function (req, res){

      new rescueData({properties:{title: req.body.title, description:  req.body.description},geometry:{
     coordinates:req.body.coordinates}}).save(function (e, result) {
             console.log(result);
         });
     res.redirect('/mountain_rescue');
  });

查看

<div id="AddingPanel">
  <form method="post" action="mountain_rescue" >
      Title:<input type="text" name="title">
      Description:<textarea type="text" name="description"></textarea>
      Coordinates:<input type="text" name="coordinates">
      <button type="submit">Add</button>
  </form>

:一个空的段落标签。

你可以以“点”为例,但你可能想要处理各种类型的特征,具有不同类型的坐标(对于点来说是数组,对于线串来说是数组的数组,对于多边形和多线串来说是数组的数组的数组)。 - Eric Burel
3个回答

16

GeoJSON 字段必须包含一个几何类型作为字符串。因此,GeoJSON 字段必须定义如下:

geometry: { type: { type: String }, coordinates: [Number] }

或者如果你想定义一个默认值,可以使用以下这行代码:

geometry: { type: { type: String, default:'Point' }, coordinates: [Number] }

祝你好运。


仅适用于Point类型,不适用于任何GeoJSON字段。 - Eric Burel

10

像这样;

var DataSchema = new Schema({
  properties: {
    title:       { type: String, required: true },
    description: { type: String, required: true },
    date:        { type:Date, default:Date.now }
  },
  geometry: {
    coordinates: { type: [Number], index: '2dsphere'}
  }
});

这是您的更新路由处理程序,它将坐标字符串转换为数字数组。

app.post('/mountain_rescue',  function (req, res) {
  new rescueData({
    properties: {
      title: req.body.title, description: req.body.description
    },
    geometry: {
      coordinates:req.body.coordinates.split(',').map(Number)
    }
  }).save(function (e, result) {
    console.log(result);
  });
  res.redirect('/mountain_rescue');
});

我不明白,我应该将 [3.43, 4.3343] 输入吗? - Igor
1
不,当它到达服务器时仍然是一个字符串,请尝试像这样做:req.body.coordinates.split(',').map(Number),它将返回一个数字数组。 - Safi
我按照你说的做了,但没有使用.map(Number),但仍然很好用,我应该使用.map(Number)吗? - Igor
1
不,这只是为了确保字符串被转换为数字,而这似乎已经由驱动程序完成了。 - Safi
2
如果以后想要执行地理空间查询,则需要这个。如果不需要进行此操作,则不需要。 - Safi
显示剩余3条评论

1

try this:

var DataSchema = new Schema({
  properties: {
    title:       { type: String, required: true },
    description: { type: String, required: true },
    date:        { type:Date, default:Date.now }
  },
  geometry: {
       coordinates: {type: Array, required: true}
  }
});

我以前试过,在mongodb中结果是这样的:"coordinates":["1.434343, 4.21322"],而且带有这些引号无法作为geojson读取,我在我的以前的项目中进行了检查。但我很好奇为什么如果它是一个数组,mongo会放置引号? - Igor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接