[英]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. 我一直在使用猫鼬和地理空间搜索,在学习了教程并阅读了此处的内容之后,我仍然无法解决这个问题。
My schema: 我的架构:
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);
My (POST) route: 我的(POST)路线:
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);
});
});
My (GET) route: 我的(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);
});
});
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.
例如,如果我搜索的位置与数据库中的位置相距200m,即使我输入?distance = 1(KM),也不会得到结果,但是如果输入300(km)之类的信息,我会得到一些结果结果。 Distance doesn't match at all.
距离根本不匹配。
What am I doing wrong? 我究竟做错了什么?
Thanks 谢谢
I was able to fix it this way reading the docs: 我可以通过阅读文档来解决此问题:
index: '2dsphere' requires this query: 索引:“ 2dsphere”需要以下查询:
$near :
{
$geometry: { type: "Point", coordinates: [ <lng>, <lat> ] },
$minDistance: <minDistance>,
$maxDistance: <maxDistance>
}
}
and not this one which is meant to be used for the legacy index: '2d': 而不是要用于旧索引的“ 2d”:
loc: {
$near: [<lng>, <lat>],
$maxDistance: <maxDistance>
}
I hope this will help someone :) 我希望这会帮助某人:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.