GeoJSON/mongoose GeoJSON模式/简介

GeoJSON/mongoose GeoJSON模式/简介,mongoose,geojson,hapijs,Mongoose,Geojson,Hapijs,当我试图学习Hapi/Mongoose/Mongo时,新手提出了问题和困惑 我的任务是简单地创建一个包含文本和地理位置点(lat&lon)的模型/对象,并使用提供的当前lat&lon从数据库检索这些对象 尝试使用mongoose geojson模式包创建模式 “猫鼬”:“^4.11.1”, “mongoose geojson模式”:“^2.1.2” 型号: const GeoJSON=require('mongoose-GeoJSON-schema'); const mongoose=requi

当我试图学习Hapi/Mongoose/Mongo时,新手提出了问题和困惑

我的任务是简单地创建一个包含文本和地理位置点(lat&lon)的模型/对象,并使用提供的当前lat&lon从数据库检索这些对象

尝试使用mongoose geojson模式包创建模式

“猫鼬”:“^4.11.1”,
“mongoose geojson模式”:“^2.1.2”

型号:

const GeoJSON=require('mongoose-GeoJSON-schema');
const mongoose=require('mongoose');
const Schema=mongoose.Schema;
const Point=mongoose.Schema.Types.Point
const postModel=新模式({
_所有者:{type:String,ref:'User'},
文本:{type:String},
地点:点
});
创建帖子:

let post = new Post();
post._owner = req.payload.user_id;
post.text = req.payload.text;

var point = new GeoJSON({
  point: {
  type: "Point",
  coordinates: [req.payload.lat, req.payload.lon]
  }
})
post.loc = point

不断获取错误
GeoJSON不是日志中的构造函数。尝试了不同的变体,并获得了其他错误,如路径“loc”处的值“{type:'Point',坐标:['39.0525909','-94.5924078']}”的
loc:Cast to Point失败我发现mongoose geojson模式包使用起来很麻烦。如果只是存储点,请将模型更改为:

const postModel = new Schema({
  _owner: { type: String, ref: 'User' },
  text: { type: String },
  loc: {
    type: { type: String },
    coordinates: [Number]
  }
});
接下来,将向后存储坐标。虽然我们通常会想到lat/lon,但在GIS世界中,我们认为lon/lat.GeoJson也不例外。从x/y的角度考虑,它会有意义。因此,将您的创建更改为:

post.loc = {
  type: 'Point',
  coordinates: [req.payload.lon, req.payload.lat]
}
在这一点上,它将正确地存储在mongo中,但它不会有多大用处,因为您将无法对它进行搜索或计算。最后需要做的是添加一个2dsphere索引

postModel.index({'loc': '2dsphere'});
现在你该走了。您可以在与点的给定距离内找到立柱:

postModel.find({
  loc:{
    $geoWithin: { $centerSphere: [ [ -105.42559,36.55685 ], 10 ] }
  }
}).exec()

我发现MongooseGeoJSON模式包很讨厌使用。如果只是存储点,请将模型更改为:

const postModel = new Schema({
  _owner: { type: String, ref: 'User' },
  text: { type: String },
  loc: {
    type: { type: String },
    coordinates: [Number]
  }
});
接下来,将向后存储坐标。虽然我们通常会想到lat/lon,但在GIS世界中,我们认为lon/lat.GeoJson也不例外。从x/y的角度考虑,它会有意义。因此,将您的创建更改为:

post.loc = {
  type: 'Point',
  coordinates: [req.payload.lon, req.payload.lat]
}
在这一点上,它将正确地存储在mongo中,但它不会有多大用处,因为您将无法对它进行搜索或计算。最后需要做的是添加一个2dsphere索引

postModel.index({'loc': '2dsphere'});
现在你该走了。您可以在与点的给定距离内找到立柱:

postModel.find({
  loc:{
    $geoWithin: { $centerSphere: [ [ -105.42559,36.55685 ], 10 ] }
  }
}).exec()

谢谢,我最后也走了这条路!谢谢,我最后也走了这条路!