Mongoose地理查询不会返回正确的结果
我想查询一个数据库,我正在存储的位置坐标附近的某个坐标,还指定一个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 )纬度= 33.901948和长= 35.576797和纬度= 33.377796和长= 35.480911之间的距离为58公里,明显大于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-索引。
- 2dsphere index if specifying a GeoJSON point - 2d index if specifying a point using legacy coordinates.
您的模式使用传统坐标字段。 这不是一个GeoJSON字段。 因为GeoJSON必须包含一个像下面这样的坐标types的值;
location: { 'type': { type: String, default: 'Point' }, coordinates: [Number] }
如果你想要传统的坐标字段,你应该使用2d
索引。
2-纬度的顺序。 和lng。 您的代码必须以“ Longitude
开头
IMPORTANT Specify coordinates in this order: “longitude, latitude.”
另一方面,如果你想使用传统的2D索引,你可以使用下面的代码 ;
{ location : { $near : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
上面的代码有一个$maxDistance
参数,用于指定radius
。 我想你应该检查一下。 因为您必须考虑以下线路以find5米距离。
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); } )
我希望这有助于,祝你好运!