【问题标题】:What is wrong with my node.js MongoDB 2dsphere find() call?我的 node.js MongoDB 2dsphere find() 调用有什么问题?
【发布时间】:2016-08-25 15:17:31
【问题描述】:

在 mongodb 中,我有两个集合可以帮助我回答问题 "Where are the cell towers in my state?"

第一个集合是根据人口普查数据创建的,它具有州边界的多边形。

第二个集合是通过下载 OpenCellId 数据库并将其导入而创建的。 “l”是塔的位置坐标键。

javascript 代码需要获取状态,然后打印该状态下的塔。

我已使用内华达州多边形的文本(复制/粘贴)代替find() 调用中的 stateBounds 变量来完成此操作。

但是当传递完全相同的对象而不是复制/粘贴时,console.log("Tower found: %j", item); 调用会打印 "Tower found: [Circular]"

const mongoUrl  = 'mongodb://localhost:27017/test';
const hostname  = '127.0.0.1';
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(mongoUrl, function(err, db){ 
    var towers  = db.collection('celltowers');
    var states  = db.collection('states');
    states.findOne({"properties.STUSPS": "NV"},function(err, item){
        getTowers(towers, item);
    }); 

});

function getTowers(celltowers, state) {
    var stateBounds = JSON.stringify(state, "geometry.coordinates");
    celltowers.find({l:{$geoWithin:{$geometry:{type: "Polygon", coordinates: stateBounds}}}}, function(err, item) {
        console.log("Tower found: %j", item);
    }); 
}

我需要为celltowers.find() 使用 geojson 多边形。

我能做些什么来解决这个问题?

【问题讨论】:

  • 您能说出代码JSON.stringify(state, "geometry.coordinates"); 中这一行的意图吗?您可以添加控制台并检查stateBounds 的值吗?合适吗?
  • 那个 JSON.stringify 选择了 geojson 状态的属性。我只需要选择的坐标和地址(如果你愿意的话)是geometry.coordinates。通过复制和粘贴该调用的结果并替换 stateBounds,find() 起作用了。所以我认为这是正确的,因为复制/粘贴有效。
  • 你尝试使用 Json 的方式。 Stringy 不是正确的方法。请参考一些文档以了解如何从 Json 对象中获取所需的字段。
  • 使用 state['geometry.coordinates'] 和 JSON.stringify(state, "geometry.coordinates") 会导致同样的问题(他们都选择了多边形)。我对 [Circular] 错误感到困惑,这里有什么可能是循环的?

标签: node.js mongodb mongodb-query geojson


【解决方案1】:

假设您的数据库如下:

{
   //Some more fields as well
   geometry:{coordinates : [0,12]};
}

您尝试的是查询不正确。您尝试将整个记录,即state 提供为coordinates。相反,您应该在查找查询中给出记录中的坐标值。

这可能会解决您的问题:-

function getTowers(celltowers, state) {
  var stateBounds = JSON.stringify(state);

  celltowers.find({l:{$geoWithin:{$geometry:
  {
     type: "Polygon", 
     coordinates: stateBounds.geometry.coordinates //Change is here.
  }
  }}}, function(err, item) 
  {
    console.log("Tower found: %j", item);
  });
}

您可以参考doc了解更多使用方法。

【讨论】:

  • 以下行仅将状态坐标分配给传递给 find() 的 stateBounds 变量: var stateBounds = JSON.stringify(state, "geometry.coordinates");
  • 你控制台检查过吗?当我尝试时,它给了我整个对象。
  • 是的。粘贴打印到控制台的内容时,它可以工作。那是踢球者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
  • 2015-11-01
  • 2016-01-29
  • 2015-03-23
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多