Mongo(+ Mongoose)错误:无法找到$ geoNear查询的索引

时间:2014-11-09 21:40:04

标签: node.js mongodb express mongoose geo

这是我的架构:

var ActivitySchema = new Schema({
    loc: {type: [Number], index: '2dsphere'}
});

当我试图找到附近的文件时:

Activity.find().where('loc').near({
        center: [-71.072810, 42.370227],
        spherical: true
    }).exec(function(err, docs){
        if (err) console.log(err);
        console.log(docs);
    })

这就是我得到的:

  

{[MongoError:无法执行查询:错误处理查询:   ns = bunch-test.activities limit = 0 skip = 0树:GEONEAR字段= loc   maxdist = 1.79769e + 308 isNearSphere = 1 Sort:{} Proj:{} planner   返回错误:无法找到$ geoNear查询的索引名称:   ' MongoError' }

我尝试过以多种方式定义loc。例如:

loc: {
        type: {
            type: String,
            enum: 'Point',
            default: 'Point'
        },
        coordinates: {
            type: [Number],
            default: [0,0],
        }
    }

也以多种方式查询:

Activity.find({
        loc: {
            $nearSphere: {
                $geometry: {
                    type: "Point" ,
                    coordinates: [ -71.072810, 42.370227 ]
                },
                $minDistance: 0,
                $maxDistance: 10000,
            }
        }
    })

或:

Activity.geoNear({
   type: "Point" ,
   coordinates: [ -71.072810, 42.370227 ]
},
{ maxDistance : 99999999999,
  spherical : true 
},
function(err, results, stats) {
   console.log(results);
   console.log(err);
});

但结果始终是相同的信息:

  

无法找到$ geoNear查询的索引

有什么建议吗?感谢。

1 个答案:

答案 0 :(得分:3)

只有在使用Mocha进行测试时才会出现问题。我之后(功能(完成)});在每个测试文件的末尾都删除整个数据库,并且在下一次测试时没有再创建索引。

我通过将mongoose.connection.db.dropDatabase替换为Model.remove({},callback)解决了这个问题;