Mongoose Schema for geoJson coordinates

末鹿安然 提交于 2020-08-21 17:00:18

问题


I tried to create a schema for geojson but have had some problems with syntax for coordinates.

Here's my current code:

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

I tried using [] (empty array), it creates '' and [Number,Number] but it doesn't work.

My question is: how do I have to construct my schema so as result I will get

coordinates: [ 3.43434343, 5.543434343 ]

without quotation marks, is this possible?

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

View

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


回答1:


Like 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: [Number], index: '2dsphere'}
  }
});

Here is your update route handler, it converts coordinates string to number array;

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



回答2:


A GeoJSON field has to be included a geometry type as a string. So a GeoJSON field must be defined like the following;

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

or if you want to define a default value you might use the below line;

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

Good luck..




回答3:


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


来源:https://stackoverflow.com/questions/28749471/mongoose-schema-for-geojson-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!