【问题标题】:geospatial queries on subdocuments对子文档的地理空间查询
【发布时间】:2014-07-18 08:43:01
【问题描述】:

我有一个猫鼬模式,其子文档包含一个位置字段(带有 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。查询如下所示:

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

我还通过 mongo 检查了索引确实存在:

> 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
    }
]

我做错了什么?提前致谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您确定您使用的是正确的集合吗?默认情况下,Mongoose 会将您的收藏名称复数(所以 players 而不是 player)。

    下面的脚本对我有用。出于某种原因,当在架构中指定 2dsphere 索引时,Mongoose 没有为我创建索引,因此我将其移出。

    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)
    });
    

    【讨论】:

    • 我注意到我有一个错字:它是 index: '2dsphere' 而不是 index: '2dSphere'
    猜你喜欢
    • 1970-01-01
    • 2014-08-23
    • 2015-06-07
    • 2013-09-25
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多