node.js - 蒙戈 (+ Mongoose ) 错误 : Unable to find index for $geoNear query

标签 node.js mongodb express mongoose geo

这是我的架构:

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: Unable to execute query: error processing query: ns=bunch-test.activities limit=0 skip=0 Tree: GEONEAR field=loc maxdist=1.79769e+308 isNearSphere=1 Sort: {} Proj: {} planner returned error: unable to find index for $geoNear query] name: '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);
});

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

unable to find index for $geoNear query

有什么建议吗?谢谢。

最佳答案

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

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

关于node.js - 蒙戈 (+ Mongoose ) 错误 : Unable to find index for $geoNear query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833647/

相关文章:

javascript - toLocaleDateString 返回字符串而不关心语言环境

mongodb - 为什么 mongodump 不备份索引?

mysql - 如何在 Node JS 上使用一对多关系表从 mysql 查询 js 创建 json 结果?

node.js - 调用 ExpressJS REST 路由时出现奇怪的行为

mysql - 当我转到特定路线时,即使它不存在,也会呈现错误的 ejs 文件。 NodeJs

node.js - 自动化 Node.js 构建

javascript - 用于 JavaScript 服务器开发的最佳 IDE

node.js - 标准输入读取某些输入失败

node.js - Mongoose 中的过滤、排序和分页返回重复值

javascript - 无法通过js连接mongo db