当我试图学习Hapi / Mongoose / Mongo时,新手的问题和困惑。
我的任务是想简单地创建一个包含文本和地理位置点(经度)的模型/对象,并可以使用提供的当前经度从数据库中检索这些对象(&L
尝试使用mongoose-geojson-schema包创建模式
"mongoose": "^4.11.1", "mongoose-geojson-schema": "^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 = new Schema({
_owner: { type: String, ref: 'User' },
text: { type: String },
loc: Point
});
创建帖子:
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 is not a constructor
。尝试了不同的变体,并得到了其他错误,如loc: Cast to Point failed for value "{ type: 'Point', coordinates: [ '39.0525909', '-94.5924078' ] }" at path "loc"
发布于 2017-11-01 01:40:35
我发现mongoose-geojson-schema包使用起来很麻烦。如果您只是简单地存储点,请将模型更改为:
const postModel = new Schema({
_owner: { type: String, ref: 'User' },
text: { type: String },
loc: {
type: { type: String },
coordinates: [Number]
}
});
接下来,向后存储坐标。虽然我们通常考虑的是经度/经度,但在GIS世界中,我们考虑的是经度/经度。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()
https://stackoverflow.com/questions/46493986
复制相似问题