2014-07-17 40 views
3

我有一個包含位置字段(帶有2dSpehre索引)的子文檔的貓鼬模式。就像這樣:關於子文檔的地理空間查詢

var playerSchema = new mongoose.Schema({ 
    name: { type: String, required: true }, 
    addresses: [ 
     { 
      address: { 
       street: String, 
       city: String, 
       zip: String, 
       country: String 
      }, 
      loc: { type: [Number], index: '2dSphere' } 
     } 
    ], 
}); 

當我嘗試查詢通過地理信息運營商,我得到這個錯誤地址:planner returned error: unable to find index for $geoNear query。查詢看起來是這樣的:

> db.player.getIndexes() 
[ 
    { 
     "v" : 1, 
     "key" : { 
      "_id" : 1 
     }, 
     "name" : "_id_", 
     "ns" : "project.player" 
    }, 
    { 
     "v" : 1, 
     "key" : { 
      "addresses.loc" : "2dsphere" 
     }, 
     "name" : "addresses.loc_2dsphere", 
     "ns" : "project.player", 
     "2dsphereIndexVersion" : 2 
    } 
] 

我在做什麼錯:

var query = { 
    'addresses.loc': { 
     $nearSphere: { 
      $geometry: { type: 'Point', coordinates: [16.3738189, 48.2081743] } 
     } 
    } 
}; 
Player.find(query).exec(); 

我還可以通過該指數真的存在蒙戈檢查?提前致謝。

回答

3

您確定您使用的是正確的系列?貓鼬會默認複製你的收藏名稱(所以players而不是player)。

下面的腳本正在爲我工​​作。出於某種原因,當Mongoose在模式中指定時,它並沒有爲我創建2dsphere索引,因此我將其移除了。

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

var playerSchema = new mongoose.Schema({ 
    name: { type: String, required: true }, 
    addresses: [ 
     { 
      address: { 
       street: String, 
       city: String, 
       zip: String, 
       country: String 
      }, 
      loc: { 'type': { type: String }, 'coordinates': { type: [Number] } } 
     } 
    ], 
}); 

playerSchema.index({'addresses.loc': '2dsphere'}); 
var Player = mongoose.model('Player', playerSchema); 

mongoose.connect('mongodb://localhost/test'); 

var query = Player.find({ 
    'addresses.loc': { 
     $nearSphere: { 
      $geometry: { type: 'Point', coordinates: [16.3738189, 48.2081743] } 
     } 
    } 
}, function (err, players) { 
    console.log(err) 
    console.log(players) 
}); 
+0

我注意到我有一個錯字:它是'index:'2dsphere'而不是'index:'2dSphere'。 – kleinph