2015-06-07 63 views
2

我有以下架構,我在地理座標上有2d索引。

var mongoose = require("mongoose"); 
var Schema = mongoose.Schema; 

var LocationSchema = new Schema ({ 
    geo: { 
     type: [Number], 
     required: true, 
     index: "2dsphere" 
    } 
}); 

module.exports = mongoose.model("Location", LocationSchema); 

我想找到新的位置:

Location.find({ 
    geo: { 
     $nearSphere: [req.query.lat, req.query.lng], 
     $maxDistance: maxDistance 
    } 
}, function(err, events) { 
    if (err) { 
     console.log(err); 
     res.status(500).json(err); 
    } 
    res.status(200).json(events); 
}); 

該指數似乎要創建:

> db.system.indexes.find(); 
{ "v" : 1, "key" : { "geo" : "2dsphere" }, "name" : "geo_2dsphere", "ns" : "dev.events", "background" : true, "safe" : null, "2dsphereIndexVersion" : 2 } 

雖然我在這裏創造一個指標,我得到時,我想下面的錯誤找到附近的地點:

{ [MongoError: Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0 
Tree: GEONEAR field=loc maxdist=0.156961 isNearSphere=0 
Sort: {} 
Proj: {} 
planner returned error: unable to find index for $geoNear query] 
name: 'MongoError', 
message: 'Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0\nTree: GEONEAR field=loc maxdist=0.156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query', 
'$err': 'Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0\nTree: GEONEAR field=loc maxdist=0.156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query', 
code: 17007 } 

回答

0

你已經在你的位置架構中定義的「地理」和你正在使用

loc : { 
     $nearSphere: [req.query.lat, req.query.lng], 
     $maxDistance: maxDistance 
     } 

更改它尋找到

geo : { 
     $nearSphere: [req.query.lat, req.query.lng], 
     $maxDistance: maxDistance 
     } 
+0

嗨,這不是問題。仍然得到相同的錯誤。 – user2500558

+0

根據mongodb查詢$ nearSphere給出第一個經度和緯度:[req.query.lng,req.query.lat]。希望它會起作用 –

6

Mongo Docs蒙戈使用[經度,緯度],在這裏你正在使用的相反。

+0

是的這是非常重要的!每個人都需要記住這一點! –

2

將解析數據庫遷移到AWS後,我遇到了類似的問題。 我通過

db.prod.createIndex({ "location": "2d" }) 

解決了這個問題,即督促是我收集的名稱和位置是列名其中存儲的地理位置信息(GeoPoint對象)

討論相關& geoNear可以在geo location issue(github)

0

被發現確保您的查詢中的字段名稱與架構中的名稱匹配。對於我的這個錯誤來了,因爲我的模式有'loc',並且查詢正在搜索'lastLocation'。

var mongoQuery = User.find({ 
       lastLocation: { 
        $near: coordinates, 
        $maxDistance: maxDistance 
       } 
      }).limit(limit); 

var UserSchema = new mongoose.Schema({ 
    //... 
    lastLocation: { 
     type: [Number], 
     index: '2d' 
    } 
});