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

3
这是我的模式(Schema):
var ActivitySchema = new Schema({
    loc: {type: [Number], index: '2dsphere'}
});

当我尝试使用“near”查找文档时:

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 Tree: GEONEAR field=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个回答

3

这个问题只在使用Mocha进行测试时才会出现。我的after(function(done))会在每个测试文件结束时清空整个数据库,但是索引不会再次创建,以用于下一次测试。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接