Mongoose地理查询不会返回正确的结果

时间:2015-02-25 23:17:09

标签: node.js mongodb mongoose geolocation

我正在尝试查询数据库,其中我存储了某些坐标附近的位置坐标,并指定了maxDistance。 我在官方mongo文档中读到maxDistance以米为单位。 集合架构如下:

var BranchSchema = new Schema({
parentId: {
    type: Schema.Types.ObjectId,
    required: 'The ID of the parent is required.',
    index: true
},
name: {
    type: 'String',
    required: 'The branch name is required.'
},
location: {
    type: [Number],
    index: {
        type: '2dsphere'
    }
}
});

我插入了一份包含以下信息的文件:

{
"parentId" : ObjectId("54ee08c2d903aca72291f120"),
"name" : "Branch1",
"_id" : ObjectId("54ee422809f242122744990c"),
"location" : [ 
    33.377796, 
    35.480911
]
}

然后我尝试查询lat = 33.901948和long = 35.576797,最大距离为5。 我在网上使用了一个在线工具(http://www.movable-type.co.uk/scripts/latlong.html),它给出lat = 33.901948和long = 35.576797之间的距离,lat = 33.377796和long = 35.480911为58KM,显然大于5米,但查询仍返回结果虽然它不应该

mongoose查询如下:

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

提前致谢

1 个答案:

答案 0 :(得分:2)

实际上,我在你的问题上看到了一些错误;

1-指数。

 - 2dsphere index if specifying a GeoJSON point
 - 2d index if specifying a point using legacy coordinates.

您的架构使用旧版坐标字段。它不是GeoJSON字段。因为GeoJSON必须包含一个坐标类型值,如下所示;

location: {
            'type': { type: String, default: 'Point' },
             coordinates: [Number]
           } 

如果您想要传统坐标字段,则应使用2d索引。

2-纬度的顺序。和lng。   您的代码必须start with Longitude

IMPORTANT
Specify coordinates in this order: “longitude, latitude.”

另一方面,如果您想使用传统的2d索引,可以使用the following codes;

{ location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }

以上代码有一个$maxDistance参数,用于指定radius。我想你应该检查一下this。因为你必须考虑下面一行才能找到5米的距离。

5 meters = (5 / 6371000) radius of the earth

所以,我认为以下代码有效;

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

Branch.find(
    { location : { $near : [ -73.9667, 40.78 ], $maxDistance: 5/6371000 }}, 
    function (err, branches) {
        if (err) {
            return res.status(400)
            .send({
                message: errors.getErrorMessage(err)
            })
        }
        return res.json(branches);
    }
)  

我希望这有帮助,祝你好运!

相关问题