node.js - 即使创建了索引,也无法找到 $geoNear 查询的索引

标签 node.js mongodb mongoose

我有以下架构,我在地理坐标上有一个 2d 索引。

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

var LocationSchema = new Schema ({
    geo: {
        type: [Number],
        required: true,
        index: "2dsphere"
    }
});

module.exports = mongoose.model("Location", LocationSchema);

我想寻找新的地点:

Location.find({
    geo: {
        $nearSphere: [req.query.lat, req.query.lng],
        $maxDistance: maxDistance
    }
}, function(err, events) {
    if (err) {
        console.log(err);
        res.status(500).json(err);
    }
    res.status(200).json(events);
});

索引似乎已创建:

> db.system.indexes.find();
{ "v" : 1, "key" : { "geo" : "2dsphere" }, "name" : "geo_2dsphere", "ns" : "dev.events", "background" : true, "safe" : null, "2dsphereIndexVersion" : 2 }

虽然我在这里创建了一个索引,但当我想查找附近的位置时出现以下错误:

{ [MongoError: Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0
Tree: GEONEAR  field=loc maxdist=0.156961 isNearSphere=0
Sort: {}
Proj: {}
planner returned error: unable to find index for $geoNear query]
name: 'MongoError',
message: 'Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0\nTree: GEONEAR  field=loc maxdist=0.156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
'$err': 'Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0\nTree: GEONEAR  field=loc maxdist=0.156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
code: 17007 }

最佳答案

来自 Mongo Docs Mongo 使用 [longitude, latitude],这里你使用的是相反的。

关于node.js - 即使创建了索引,也无法找到 $geoNear 查询的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693047/

相关文章:

node.js - 了解 Node 中的非阻塞 IO

node.js - Mongoose getter 和 setter 无法正常工作

javascript - 如何从 JSON 文件目录向 mongoDB 添加许多记录?

mongodb 副本集主机 "stateStr": "REMOVED"

mongodb - 模型上的 Mongoose findOne 是否返回 promise ?

node.js - collection.find().property 返回未定义

javascript - Node js退出前的清理工作

当通过 docker-compose 运行但通过 docker 工作时,Mongodb 无法在主机上访问

node.js - MongoDB/Mongoose 保存并获取错误的整数

node.js - Mongoose 错误 : You can not `mongoose.connect()` multiple times while connected