猫鼬地理查询没有 return 正确的结果

Mongoose geo query does not return correct result

我正在尝试查询一个数据库,我在其中存储特定坐标附近位置的坐标并指定了 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
]
}

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

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- 索引。

 - 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-纬度的顺序。和液化天然气。 您的代码必须 start with Longitude

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

另一方面,如果您想使用传统的二维索引,您可以使用 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);
    }
)  

希望对您有所帮助,祝您好运!