NodeJS Rest Services将参数传递给$near查询MongoDB



我用NodeJS和MongoDB开发了一个Rest Services列表。其中一个服务执行 $near mongodb 查询,以按特定位置检索特定范围内的所有元素

 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);
    });
});

该服务是一项获取服务,运行良好。现在我想通过服务传递$near查询最大距离值和坐标,我只尝试以这种方式对最大距离:

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);
    });
});

但是当我在邮递员中运行该服务时,响应是错误"获取数据时出错"。任何帮助如何将此值作为参数传递给服务$near查询?谢谢

Express 将所有传入的值视为字符串。 将最大距离转换为整数应该有效。

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

最新更新