2017-09-29 60 views
0

新手問題和混亂,因爲我正在學習Hapi/Mongoose/Mongo。GeoJSON/mongoose-geojson-schema /介紹混淆

負責自己有想簡單地創建一個模型/對象包含文本和地理位置點(LAT & LON),並且可以使用所提供的電流LAT & LON

檢索數據庫這些對象試圖建立一個模式使用貓鼬-以GeoJSON-架構包

"mongoose": "^4.11.1", "mongoose-geojson-schema": "^2.1.2"

型號:

const GeoJSON = require('mongoose-geojson-schema'); 
const mongoose = require('mongoose'); 

const Schema = mongoose.Schema; 
const Point = mongoose.Schema.Types.Point 

const postModel = new Schema({ 
    _owner: { type: String, ref: 'User' }, 
    text: { type: String }, 
    loc: Point 
}); 

創建帖子:

let post = new Post(); 
post._owner = req.payload.user_id; 
post.text = req.payload.text; 

var point = new GeoJSON({ 
    point: { 
    type: "Point", 
    coordinates: [req.payload.lat, req.payload.lon] 
    } 
}) 
post.loc = point 

保持在日誌中發現了錯誤GeoJSON is not a constructor。試過不同的變化,並得到了其他的錯誤,如loc: Cast to Point failed for value "{ type: 'Point', coordinates: [ '39.0525909', '-94.5924078' ] }" at path "loc"

回答

1

我發現了mongoose-geojson-schema包使用麻煩。如果您只是簡單地存儲一個點,請將模型更改爲:

const postModel = new Schema({ 
    _owner: { type: String, ref: 'User' }, 
    text: { type: String }, 
    loc: { 
    type: { type: String }, 
    coordinates: [Number] 
    } 
}); 

接下來,您正在向後存儲座標。雖然我們通常會想到緯度/經度,但在GIS世界中,我們認爲緯度/緯度。 GeoJson也不例外。想想它在x/y方面,這將是有道理的。所以,你的創作更改爲:

post.loc = { 
    type: 'Point', 
    coordinates: [req.payload.lon, req.payload.lat] 
} 

此時它會在蒙戈正確地存儲,但它不會是多大用處,因爲你將無法搜索或做任何數學。你需要做的最後一件事是添加一個2dsphere索引。

postModel.index({'loc': '2dsphere'}); 

現在你應該很好去。你可以在一個點的給定距離內找到帖子:

postModel.find({ 
    loc:{ 
    $geoWithin: { $centerSphere: [ [ -105.42559,36.55685 ], 10 ] } 
    } 
}).exec() 
+0

謝謝,我最終也是這樣的! – ndyr