问题
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"
}
from typing in: http://localhost:3000/api/locations?lng=-133.482946&lat=45.263776
my code is as follows:
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);
}
});
};
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.
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.
回答1:
The comment about ensuring you have a geospatial index is right. Try this...
db.locations.ensureIndex({coords: '2dsphere'})
来源:https://stackoverflow.com/questions/39842475/mongoerror-reports-no-indices-when-passed-indices-through-url-using-geonear