[英]Mongoose geospatial search: distance not working
我一直在使用貓鼬和地理空間搜索,在學習了教程並閱讀了此處的內容之后,我仍然無法解決這個問題。
我的架構:
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)路線:
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)之類的信息,我會得到一些結果結果。 距離根本不匹配。
我究竟做錯了什么?
謝謝
我可以通過閱讀文檔來解決此問題:
索引:“ 2dsphere”需要以下查詢:
$near :
{
$geometry: { type: "Point", coordinates: [ <lng>, <lat> ] },
$minDistance: <minDistance>,
$maxDistance: <maxDistance>
}
}
而不是要用於舊索引的“ 2d”:
loc: {
$near: [<lng>, <lat>],
$maxDistance: <maxDistance>
}
我希望這會幫助某人:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.