user5858205 user5858205 - 6 months ago 35
Node.js Question

NodeJS Rest Services passing parameter to $near query MongoDB

i have develop a list of Rest Services with NodeJS and MongoDB. One of these service execute a $near mongodb query to retrive all element into a specific range by a specific position

router.route("/api/geo_cars")
.get(function(req,res){
var max = 1000;
var response = {};
mongoOOp.find({
location:
{ $near :
{
$geometry: { type: "Point", coordinates: [ 12.560945, 41.957482 ] },
$maxDistance: max
}
}
},function(err,data){
// Mongo command to fetch all data from collection.
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
});


The service is a get service and works very well.
Now i woutld like to pass to $near query the maxDistance value and coordinates by Service and i have try in this way for only maxDistance:

router.route("/api/geo_cars/:maxDistance")
.get(function(req,res){
var max = req.params.maxDistance;
var response = {};
mongoOOp.find({
location:
{ $near :
{
$geometry: { type: "Point", coordinates: [ 12.560945, 41.957482 ] },
$maxDistance: max
}
}
},function(err,data){
// Mongo command to fetch all data from collection.
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
});


but when i run the service in postman the response is a error "Error fetching data".
Any help how i can pass this value to $near query by service as parameter?
Thanks

Ben Ben
Answer

Express treats all values passing in as strings. Converting maxDistance to integer should work.

var max = parseInt(req.params.maxDistance);
Comments