【问题标题】:Passing variables into node.js mongoose find query将变量传递给 node.js mongoose 查找查询
【发布时间】:2011-12-28 23:40:12
【问题描述】:

希望大家帮忙。我对 node.js / mongodb 还很陌生,我在将变量传递给 mongoose 模型查询时遇到了麻烦。

如果我运行此程序,手动将经度/纬度(-0.18、51.24)作为字符串传递,那么它可以完美运行并从数据库中返回大量对象。

Venue.find( { location : { $nearSphere : [-0.18, 51.24], $maxDistance : 25/3959 } }, null, {limit: 50}, function(err, results){
    results.forEach(function(result){
       console.log('Found a record');
    });
}); 

但是,如果我尝试将这些坐标作为变量传递给在其中运行的函数,则不会返回任何结果:

function generateWorld(get) {

    console.log('Generating for x:' + get.longitude + ' y:' + get.latitude); // Console logs correct coords

    Venue.find( { location : { $nearSphere : [get.longitude, get.latitude], $maxDistance : 25/3959 } }, null, {limit: 50}, function(err, results){
        results.forEach(function(result){
           console.log('Found a record'); // <-- This doesn't return any results!
        });
    }); 

}

我确定我只是做错了一些简单的事情,但我已经为此苦苦思索了一段时间,无法克服它。任何帮助将不胜感激!

谢谢。

【问题讨论】:

  • 尝试做 get.longitude = parseFloat(get.longitude) 和 get.latitude = parseFloat(get.latitude)
  • 是的!效果很好,谢谢!
  • 我已将我的评论放在答案中,以便您可以投票并接受它,以便其他人知道它已得到回答。

标签: mongodb node.js geospatial mongoose


【解决方案1】:

您也可以在每个变量前面加上一个“+”号,将它们强制转换为数字,即,

{ $nearSphere : [+get.longitude, +get.latitude]

即使其中一个变量为负数也有效。

【讨论】:

    【解决方案2】:

    尝试做get.longitude = parseFloat(get.longitude)get.latitude = parseFloat(get.latitude)

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2019-02-16
      • 2016-12-19
      • 2017-11-25
      • 1970-01-01
      相关资源
      最近更新 更多