Javascript Mongoose/MongoDB GeoJSON查询返回空结果
我有一个包含此属性的模式(教程)。 该位置是GeoJSON点类型Javascript Mongoose/MongoDB GeoJSON查询返回空结果,javascript,angular,typescript,mongodb,mongoose,Javascript,Angular,Typescript,Mongodb,Mongoose,我有一个包含此属性的模式(教程)。 该位置是GeoJSON点类型 location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true }, index: '2dsphere' }, 用于创建巡更的控制器如下所示 const c
location: {
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
},
index: '2dsphere'
},
用于创建巡更的控制器如下所示
const createTour = async (req, res) => {
var newTour = new TourDB.Tour({
...
location: { type: 'Point', coordinates: [req.body.tour.loc[0], req.body.tour.loc[1]] },
...
})
newTour.save(async (err, doc) => {
if (!err) {
return res.status(200).send(doc)
} else {
return res.status(500).send({ errorMessage: err })
}
})
在前端,我将使用此属性创建一个新的教程loc:[this.lng,this.lat],
这是MongoDB中的结果:
如何进行查询以获取半径内的位置
我在我的控制器中尝试了这个(目前radius和maxDistance是为测试目的而硬编码的):
但现在我得到了一个空的[]返回
我做错了什么?你的距离是多少?一般来说,您的代码应该可以工作:
db.tour.insertOne({
location: { type: 'Point', coordinates: [9.8238464, 47.627712] },
cityName: "Geislingen"
})
db.tour.createIndex({ location: "2dsphere" })
let coords = [];
coords[0] = 9.825031;
coords[1] = 48.625107799999995
db.tour.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: coords },
distanceField: "distance",
spherical: true
}
}
])
返回:
{
"_id" : ObjectId("608a73d51ef0d7c449c3e4c6"),
"location" : {
"type" : "Point",
"coordinates" : [
9.8238464,
48.627712
]
},
"cityName" : "Geislingen",
"distance" : 302.71595482740787
}
使用maxDistance>302.7米返回文档:
let maxDistance = 303
db.tour.find(
{
location: {
$near: {
$geometry: { type: "Point", coordinates: coords },
$maxDistance: 303
}
}
}
)
{
"_id" : ObjectId("608a73d51ef0d7c449c3e4c6"),
"location" : {
"type" : "Point",
"coordinates" : [
9.8238464,
48.627712
]
},
"cityName" : "Geislingen"
}
注意,如果指定的点是GeoJSON,则以米为单位指定距离;如果指定的点是传统坐标对,则以弧度为单位指定距离。请不要粘贴图像,使用格式化文本作为源数据,请查看确实是距离。。。把距离扩大到5000米终于对我有用了!哇!谢谢:D
let maxDistance = 303
db.tour.find(
{
location: {
$near: {
$geometry: { type: "Point", coordinates: coords },
$maxDistance: 303
}
}
}
)
{
"_id" : ObjectId("608a73d51ef0d7c449c3e4c6"),
"location" : {
"type" : "Point",
"coordinates" : [
9.8238464,
48.627712
]
},
"cityName" : "Geislingen"
}