2015-10-16 12 views
1

我想從特定點獲取附近位置的結果。通過使用ID查找的正常方式,返回結果,但是當我嘗試使用座標查找附近位置時,沒有出現結果。我的代碼中沒有任何錯誤/警告,但也沒有任何結果。我錯過了什麼?

模型模式

var locationSchema = new Schema({ 
    fb_location: String, 
    coordinates:[] 
}); 

var feed_postSchema = new Schema({ 
    content: String, 
    location: [locationSchema], 
    image: [{ type : String }], 
    created_at: { type : Date, default: Date.now } 
}); 

locationSchema.index({coordinates:'2dsphere'}); 

Server.js

app.get('/test_radar',function(request,response){ 
    Feed_Post.find( 
    { 
     'location.coordinates' : 
     { 
      $near : 
      { 
       coordinates: [100,5] 
      }, 
      $maxDistance: 100 
     } 
    },function(err,ret){ 
     console.log(response.json(ret)); 
    }) 
}); 

示例數據庫數據

"_id" : ObjectId("5620a3c2fde01a55065f4c3b"), 
    "content" : "Test post", 
    "created_at" : ISODate("2015-10-16T07:14:10.636Z"), 
    "image" : [ ], 
    "location" : [ 
      { 
        "fb_location" : "Malaysia", 
        "_id" : ObjectId("5620a3c2fde01a55065f4c3c"), 
        "coordinates" : [ 
          100, 
          5 
        ] 
      } 
    ], 
    "__v" : 0 

注:我沒設置$ maxDistance爲100 * 1000目前仍沒有結果。

回答

1

$near運算符需要一個地理空間索引。

如果要使用舊座標將點定義爲點,則必須有2D index created。然後,您將能夠按照您指定的語法使用$near運算符。

您創建2dsphere指數,所以你必須在你的查詢中指定以GeoJSON點:

Feed_Post.find( 
    { 
     'location.coordinates' : 
     { 
      $geometry: { 
       type: "Point" , 
       coordinates: [ 100 , 5 ] 
      }, 
      $maxDistance: 100 
     } 
    },function(err,ret){ 
     console.log(response.json(ret)); 
    }) 

檢查$near定義。

+0

是的你是對的!我注意到我的錯誤。感謝你們對我的幫助! –

相關問題