我使用mongodb和mongoose作为我的应用程序的ODM。我有一份文件,里面有餐馆的位置。模型(模式)如下所示:
var locationSchema = new mongoose.Schema({
name: {type:String, required:true},
address: String,
coords: {type:[Number], index:'2dsphere', required:true},
});
这是我的样本数据:
"_id" : ObjectId("56b39d9673ff055a098dee71"),
"name" : "Holycow STEAKHOUSE",
"address" : "somewhere",
"coords" : [
106.7999044,
-6.2916982
]
然后我使用猫鼬从距离餐厅大约2公里的地方获取餐厅位置。我从mongodb doc上读到,我们必须在radiance和distanceMultiplier中提供地球半径的maxDistance参数,所以我将以下代码放入我的控制器中:
var point = {
type: "Point",
coordinates: [106.8047355, -6.2875187] // the test data, approximately 2 km from the restaurant
}
var geoOptions = {
spherical: true,
num: 10,
maxDistance: 5 / 6371 , // i set maximum distance to 5 km. to make sure I found the place.
distanceMultiplier: 6371
}
Loc.geoNear(point, geoOptions, function(err, results, stats){
var locations = [];
if(err){
console.log(err);
sendJsonResponse(res, 404, err);
} else {
results.forEach(function(doc){
locations.push({
distance: doc.dis,
name: doc.obj.name,
address: doc.obj.address,
_id: doc.obj._id
});
});
sendJsonResponse(res, 200, locations);
}
});
但未能找到餐厅。我已经阅读了两个小时的文档,但仍然没有任何线索。我的代码出了什么问题?
答案 0 :(得分:3)
试试这个:
var geoOptions = {
spherical: true,
num: 10,
maxDistance: 5 * 1000 , // Convert kilometers to meters
}
我想我们正在阅读同一本书。你的代码很熟悉,而且 我也遇到了同样的问题。
您的代码无法正常运行,因为您认为maxDistace
正在使用单位弧度。但不,naxDistance
正在使用米。您还需要删除distanceMultiplier
,因为它会将您的maxDistance
转换为弧度,这不是正确的单位。