Mongoose near(...)查询2dsphere索引字段未返回有效结果 [英] Mongoose near(...) query on 2dsphere indexed field not returning valid results

查看:237
本文介绍了Mongoose near(...)查询2dsphere索引字段未返回有效结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用mongoose的 qry.where()。near()语法查询mongodb数据库。

I am unable to query a mongodb database using mongoose's qry.where().near() syntax.

我有一个Schema,坐标存储为数组,索引为 2dsphere

I have a Schema with coordinates stored as an array, indexed as 2dsphere:

loc : { type: [Number], index: '2dsphere' }

我是使用运行mongoose查询.where()。near()

qry.where('loc').near({
    center: search.loc,
    maxDistance: search.distance * 1000
});

我启用了 mongoose.set('debug',true),并且可以看到生成的调试:

I have enabled mongoose.set('debug', true), and can see the resulting debug:

Mongoose: models.insert({ _id: ..., loc: [ 10, -20 ], type: 'apple' }) {}  
Mongoose: models.insert({ _id: ..., loc: [ 10, -20 ], type: 'orange' }) {}  



搜索坐标 [10,-20]附近的文件



Searching for documents near coordinates [ 10, -20 ]:

Mongoose: models.find({ loc: { '$near': [ 10, -20 ], '$maxDistance': 1000 } })

查询返回无结果。

The query returns no results.

我通过搜索类型证明文件在数据库中。它是我无法工作的地理空间查询。

I have proved the documents are in the database by searching on type. Its the geospatial query I can't get to work.

我正在使用 mongodb v2.6.1 mongoose v3.8.8

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

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

ModelSchema.index({type: 1, loc: 1});

ModelSchema.statics.search = function(search, cb) {
    var qry = this.find();
    if (search.types) {
        qry.where('type').in(search.types);
    }
    if (search.loc) {
        qry.where('loc').near({
            center: search.loc,
            maxDistance: search.distance * 1000
        });
    }
    qry.exec(cb);
};



摩卡测试:(test.ts)



Mocha test: (test.ts)

var q = require('node-promise'),
    should = require('should'),
    mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my-test');
var Model = require('./model');

describe('My Model', function() {
    before(function(done) {
        mongoose.set('debug', true);

        Model.remove().exec(function() {
            var create = function(promises, body) {
                var p = new q.Promise();
                var m = new Model(body);
                m.save(function(err) {
                    if (err) {
                        console.log(err);
                        p.reject();
                    } else {
                        p.resolve();
                    }
                });
                promises.push(p);
            };

            var promises = [];
            create(promises, { type: 'apple',  loc: [ 10, -20 ] });
            create(promises, { type: 'orange', loc: [ 10, -20 ] });
            create(promises, { type: 'apple',  loc: [ 15,  10 ] });
            create(promises, { type: 'orange', loc: [ 15,  10 ] });
            q.all(promises).then(function() {
                done();
            })
        });
    });

    it('should find all', function(done) {
        Model.search({}, function(err, items) {
            items.should.have.length(4);
            done();
        });
    });

    it('should find apples', function(done) {
        Model.search({types: ['apple']}, function(err, items) {
            items.should.have.length(2);
            done();
        });
    });

    // this test fails
    it('should find coords', function(done) {
        Model.search({loc: [ 10, -20 ], distance: 1}, function(err, items) {
            items.should.have.length(2);
            done();
        });
    });

});



package.json:



package.json:

{
  "name": "test",
  "version": "0.0.0",
  "dependencies": {
    "mongoose": "~3.8.8"
  },
  "devDependencies": {
    "should": "~2.1.0",
    "node-promise": "0.5.10"
  }
}



通过mocha运行:



Run through mocha:

sudo npm install -g mocha
npm install
mocha ./test.js


推荐答案

似乎这是一个 moongoose bug

将查询更改为使用 GeoJSON 对象而不是坐标对,如下所示:

Changing the query to use a GeoJSON object instead of a coordinate pair, as such:

qry.where('loc').near({
    center: {
        type: 'Point',
        coordinates: search.loc
    },
    maxDistance: search.distance * 1000
});

会产生以下查询:

Mongoose: models.find({ loc: { '$near': { 
        '$maxDistance': 1,
        '$geometry': { type: 'Point', coordinates: [ 10, -20 ] } } } 
    }) { fields: undefined }  

现在搜索成功。

docs 使用坐标对显式显示查询:

The docs explicitly show a query using a coordinate pair:

query.where('loc').near({ center: [10, 10], maxDistance: 5 });

然而,看起来这不起作用,例子应该是:

However, it looks like this doesn't work, and the example should be:

query.where('loc').near({ center: { coordinates: [10, 10], type: 'Point' }, maxDistance: 5 });

这篇关于Mongoose near(...)查询2dsphere索引字段未返回有效结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆