我已經編寫了一個應用程序,該應用程序查找本地機構並通過RESTful API提供它們。我的堆棧是:express,express-resource和mongoose。這裏是我的模型的樣本:
var PlaceSchema = new mongoose.Schema(
{
name: {
type: String,
required: true
},
geolocation: {
lat: Number,
lng: Number
},
address: {
type: String
}
}
);
PlaceSchema.index({
geolocation: '2d'
});
我檢查了幾次,我的經度/緯度值被正確地存儲在數據庫中,所以沒有任何數據錯誤。
然後我運行查詢與特定查詢的值來獲取數據:
mongoose.connection.db.executeDbCommand(
{
geoNear: 'places',
near: [
parseFloat(req.body.lat),
parseFloat(req.body.lng)
],
num: limit,
query: {
// Some additional queries that
// don't impact the geo results.
},
spherical: true,
distanceMultiplier: 6371, // converting results to km
maxDistance: distance/6371,
},
function(err, result)
{
res.send(200, {
status: true,
data: theaters
});
}
);
沒有與結果的一些問題,它的返回:一)公里計算真的錯了。在大多數情況下,有6-7公里的差異,但它有所不同,b)更接近的地方比其他地方顯得更遠。
我使用直接貓鼬查詢,因爲它會返回計算的距離(我需要我的API返回)。切換到貓鼬找到方法顯然不會讓我獲得訪問這些數據。
想知道我的索引可能是錯的嗎?它應該是2dsphere嗎?這方面的文檔有點令人困惑,但我看到的大多數示例僅使用2d。
非常感謝!
而唯一的其他建議是先在命令行中嘗試此操作,然後再在代碼中嘗試此操作。您正在使用哪種版本的MongoDB,這對正確答案有很大影響。 – TheSteve0
版本無關緊要。 MongoDB中的座標始終首先指定經度。 –
不必在版本2.2和之前 - 如果您只是使用2d索引 – TheSteve0