猫鼬地理空间搜索:距离无效 [英] Mongoose geospatial search: distance not working
问题描述
我一直在使用猫鼬和地理空间搜索,在学习了教程并阅读了此处的内容之后,我仍然无法解决这个问题.
I was playing around with mongoose and geospatial search and after following tutorials and reading stuff on here, I still couldn't ge my head around the problem.
我的模式:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
name: String,
loc: {
type: [Number], // [<longitude>, <latitude>]
index: '2dsphere' // create the geospatial index
}
});
module.exports = mongoose.model('Location', LocationSchema);
我的(POST)路线:
My (POST) route:
router.post('/', function(req, res) {
var db = new locationModel();
var response = {};
db.name = req.body.name;
db.loc = req.body.loc;
db.save(function(err) {
if (err) {
response = {
"error": true,
"message": "Error adding data"
};
} else {
response = {
"error": false,
"message": "Data added"
};
}
res.json(response);
});
});
我的(GET)路线:
router.get('/', function(req, res, next) {
var limit = req.query.limit || 10;
// get the max distance or set it to 8 kilometers
var maxDistance = req.query.distance || 8;
// we need to convert the distance to radians
// the raduis of Earth is approximately 6371 kilometers
maxDistance /= 6371;
// get coordinates [ <longitude> , <latitude> ]
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;
// find a location
locationModel.find({
loc: {
$near: coords,
$maxDistance: maxDistance
}
}).limit(limit).exec(function(err, locations) {
if (err) {
return res.json(500, err);
}
res.json(200, locations);
});
});
我能够在数据库中存储位置,但是每当我尝试搜索位置时,距离查询参数都不起作用.例如,如果我搜索的位置与数据库中的位置相距200m,即使我输入?distance = 1(KM)也不会得到结果,但是如果我输入类似300(km)的内容,我会得到一些结果结果.距离根本不匹配.
I am able to store locations in the database but whenever i try to search for a location, the distance query param doesn't work. If for example I search for a place that is 200m away from the one in the database, even if I put ?distance=1 (KM) I don't get results, but if I put something like 300 (km) I get some results. Distance doesn't match at all.
我在做什么错了?
谢谢
推荐答案
我能够通过阅读文档的方式对其进行修复:
I was able to fix it this way reading the docs:
索引:"2dsphere"需要以下查询:
index: '2dsphere' requires this query:
$near :
{
$geometry: { type: "Point", coordinates: [ <lng>, <lat> ] },
$minDistance: <minDistance>,
$maxDistance: <maxDistance>
}
}
而不是用于遗留索引"2d"的那个
and not this one which is meant to be used for the legacy index: '2d':
loc: {
$near: [<lng>, <lat>],
$maxDistance: <maxDistance>
}
我希望这会对某人有所帮助:)
I hope this will help someone :)
这篇关于猫鼬地理空间搜索:距离无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!