我使用 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
]
然后我使用 mongoose 从距离餐厅大约 2 公里的地方获取餐厅位置。我从 mongodb 文档中读到,我们必须在辐射度和距离乘数中提供 maxDistance 参数与地球半径,所以我将以下代码放入我的 Controller 中:
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);
}
});
但未能找到餐厅。我已经阅读了两个小时的文档,但仍然没有任何线索。我的代码有什么问题吗?
最佳答案
试试这个:
var geoOptions = {
spherical: true,
num: 10,
maxDistance: 5 * 1000 , // Convert kilometers to meters
}
我认为我们正在读同一本书。您的代码很熟悉,并且 我也遇到了同样的问题。
您的代码无法正常工作,因为您假设 maxDistace
使用单位弧度。但不,naxDistance
使用的是米。您还需要删除 distanceMultiplier
,因为它会将您的 maxDistance
转换为弧度,这不是正确的单位。
关于node.js - 使用 mongoose 时,geoNear() 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232423/