【问题标题】:MongoDB GeoJSON weird query resultsMongoDB GeoJSON 奇怪的查询结果
【发布时间】:2015-02-27 10:29:08
【问题描述】:

我正在使用 GeoJSON 存储我希望稍后通过邻近度查询的位置坐标,

我的架构如下所示:

'use strict';

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

var BranchSchema = new Schema({
parentId: {
    type: Schema.Types.ObjectId,
    required: 'The ID of the restaurant is required.',
    index: true
},
name: {
    type: 'String',
    required: 'The name is required.'
},
loc: {
    'type': {
        type: 'String',
        default: 'Point'
    },
    coordinates: {
        type: [Number],
        default: [0,0]
    }
}
});
BranchSchema.index({loc: "2dsphere"});
module.exports = mongoose.model('Branch', BranchSchema);

我正在使用猫鼬,我的查询如下所示:

Branch.where('loc').near({
    center: [long, lat],
    maxDistance: proximity,
    spherical: true
}).exec(function (err, branches) {
    if (err) {
        return res.status(400)
            .send({
                message: errors.getErrorMessage(err)
            });
    }
    return res.json(branches);
});

我在数据库中添加了一个新分支,其坐标如下纬度:34.237918 经度:36.002197 我用以下坐标查询数据库: 纬度:33.882957 经度:35.502319 最大距离为 100

这两个坐标相差超过100m但是数据库返回结果,我错过了什么???

【问题讨论】:

    标签: node.js mongodb mongoose coordinates geojson


    【解决方案1】:

    您能否仔细检查您是否正在执行您认为正在执行的查询?您的查询对我来说很好:

    > db.test.drop()
    > var p = { "type" : "Point", "coordinates" : [36.002197, 34.237918] }
    > var q = { "type" : "Point", "coordinates" : [35.502319, 33.882957] }
    > db.test.insert({ "loc" : p })
    > db.test.ensureIndex({ "loc" : "2dsphere" })
    > db.test.count({
        "loc" : {
            "$near" : {
                "$geometry" : q,
                "$maxDistance" : 100
            }
        }
    })
    0
    

    【讨论】:

    • 嘿@wdberkeley,非常感谢您的回复,您的代码运行良好,但是我无法使用 Mongoose 获得相同的结果,有什么想法或提示吗?
    猜你喜欢
    • 2018-09-01
    • 2021-07-22
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多