【问题标题】:NodeJS Rest Services passing parameter to $near query MongoDBNodeJS Rest Services 将参数传递给 $near 查询 MongoDB
【发布时间】:2016-09-24 11:28:58
【问题描述】:

我已经使用 NodeJS 和 MongoDB 开发了一个 Rest 服务列表。其中一项服务执行 $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 查询 maxDistance 值和坐标,我只尝试过这种方式来获取 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);
    });
});

但是当我在邮递员中运行服务时,响应是错误“获取数据时出错”。 有什么帮助我可以通过服务将这个值作为参数传递给 $near 查询吗? 谢谢

【问题讨论】:

    标签: node.js mongodb rest mongoose


    【解决方案1】:

    Express 将所有传入的值视为字符串。将 maxDistance 转换为整数应该可以。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2017-09-27
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多