2016-08-25 148 views
1

MongoDB中,我有兩個集合使用,這將幫助我解答"Where are the cell towers in my state?"我的node.js MongoDB 2dsphere find()調用有什麼問題?

首先收集從人口普查數據建立的問題,它有國家邊界的多邊形。

二集是從下載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多邊形。

我能做些什麼來解決這個問題?

+0

你能告訴什麼是這行代碼中的'JSON.stringify(州,「geometry.coordinates」)的意圖;'?你可以添加控制檯並檢查'stateBounds'的值嗎?這是否合適? – Shrabanee

+0

JSON.stringify選擇geojson狀態的屬性。我只需要座標和地址(如果您願意)選擇geometry.coordinates。通過複製並粘貼該調用的結果並替換stateBounds,find()起作用。所以我認爲這是正確的,因爲複製/粘貼工作。 –

+0

你試過用Json的方式。絲襪不是正確的方法。請參閱一些文檔,以瞭解如何從Json對象獲取所需的字段。 – Shrabanee

回答

0

假設你的數據庫如下:

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

什麼你嘗試在查詢是不正確的。您嘗試給出整個記錄,即statecoordinates。相反,您應該從find查詢中的記錄中提供座標值。

這可能會幫助您解決問題: -

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有關如何使用的詳細信息。

+0

以下代碼行只將狀態的座標分配給傳遞給find()的stateBounds變量:var stateBounds = JSON.stringify(state,「geometry.coordinates」); –

+0

你有沒有安裝並檢查它?當我嘗試時,給了我整個對象。 – Shrabanee

+0

是的。粘貼打印到控制檯的內容時可以使用。這是踢球者。 –