当使用geoNear通过URL传递索引时,MongoError不报告任何索引 [英] MongoError reports no indices when passed indices through URL using geoNear
问题描述
我正在尝试创建一个页面,该页面按距我的距离列出数据库中的位置.当我通过URL传递一组坐标时,出现此错误:
Im trying to create a page that lists locations on a database by their distance from me. When I pass in a set of coordinates via the URL I get this error:
{
"name": "MongoError",
"message": "no geo indices for geoNear",
"waitedMS": 0,
"ok": 0,
"errmsg": "no geo indices for geoNear"
}
通过输入: http://localhost:3000/api/地点?lng = -133.482946& lat = 45.263776
我的代码如下:
module.exports.locationsListByDistance = function (req, res) {
var lng = parseFloat(req.query.lng);
var lat = parseFloat(req.query.lat);
var point = {
type: "Point",
coordinates: [lng, lat]
};
var geoOptions = {
spherical: true,
maxDistance: 20000,
num: 10
};
if (!lng || !lat) {
sendJsonResponse(res, 404, {
"message": "lng and lat query parameters are required"
});
return;
}
Loc.geoNear(point, geoOptions, function(err, results, stats){
var locations= [];
if (err) {
sendJsonResponse(res, 404, err);
} else {
results.forEach(function(doc) {
locations.push({
distance: doc.dis,
name: doc.obj.name,
address: doc.obj.address,
rating: doc.obj.rating,
facilities: doc.obj.facilities,
_id: doc.obj._id
});
});
sendJsonResponse(res, 200, locations);
}
});
};
每次都会触发if语句错误,并显示上面列出的错误. 如果我控制台记录该点对象,则它会在其范围内正确显示.
It triggers the if statement error every time and the error listed above is displayed. If I console log the point object it comes up correctly within its scope.
有人对此错误有任何经验吗?有什么建议? 几个小时的搜索工作提出了可能的mongo客户端修复程序,但是由于我没有直接使用mongo客户端,因此无法作为解决方案.
Does anyone have any experience with this error? Any suggestions? Several hours of googling has come up with possible mongo client fixes but since I am not using mongo client directly it would not work as a solution.
推荐答案
关于确保您拥有地理空间索引的评论是正确的.试试这个...
The comment about ensuring you have a geospatial index is right. Try this...
db.locations.ensureIndex({coords: '2dsphere'})
这篇关于当使用geoNear通过URL传递索引时,MongoError不报告任何索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!