I've been building a small API in Express and Mongoskin. I added a simple aggregrate geoNear query to respond to params given. The server returns 200 and I get no error. I know that I'm pointing to the right collection and everything, and when I run the query in Mongo's shell it works fine. The code is below:
app.get('/collections/:collectionName/geonear', function(req, res, next) {
req.collection.aggregate([
{
"$geoNear": {
"near": [req.query.lng, req.query.lat],
"distanceField": "distance"
}
},
{
"$sort": {"distance": -1}
}
],
function(e, results) {
res.send(results);
});
});
The problem is you are passing request query strings in your near
array instead of integers, so try parsing them to return integers first using parseInt()
:
app.get('/collections/:collectionName/geonear', function(req, res, next) {
var lng = parseInt(req.query.lng),
lat = parseInt(req.query.lat);
req.collection.aggregate(
[
{
"$geoNear": {
"near": [lng, lat],
"distanceField": "distance"
}
},
{
"$sort": {"distance": -1}
}
],
function(e, results) {
res.send(results);
});
})
-- UPDATE --
From the OP @JeffLuppes:
Since this works with coordinates it's better to parse them as floats to preserve the full coordinate input. Instead of parseInt() I used parseFloat().
The revised solution is to use parseFloat()
:
app.get('/collections/:collectionName/geonear', function(req, res, next) {
var lng = parseFloat(req.query.lng),
lat = parseFloat(req.query.lat);
req.collection.aggregate(
[
{
"$geoNear": {
"near": [lng, lat],
"distanceField": "distance"
}
},
{
"$sort": {"distance": -1}
}
],
function(e, results) {
res.send(results);
});
})