Mongoose调用GeoNear与GeoJSON点作为查询参数不起作用

给定为包含GeoJSON位置的文档定义的模式;

var BranchSchema = new Schema({ location: { 'type': { type: String, required: true, enum: ['Point', 'LineString', 'Polygon'], default: 'Point' }, coordinates: [Number] }, name: String }); BranchSchema.index({location: '2dsphere'}); 

还有一些示例数据:

 [ { "name": "A", "location": { "type": "Point", "coordinates": [153.027117, -27.468515 ] //Brisbane, Australia } }, { "name": "B", "location": { "type": "Point", "coordinates": [153.029884, -27.45643] //Also Brisbane, Australia } } ] 

以下geoNear查询的行为不像预期的那样。 我读到这个查询是“给定南美海岸的一个地点,拖网穿过这些地点,并find距离所提供的地点不到1米的地方”。

 // Somewhere off the east coast of South America. var point = {type: 'Point', coordinates: [0.0776590, -33.7797590]}; Branch.geoNear(point, {maxDistance:1, spherical: true}, function (err, data) { ... // at this point I expected data.length === 0. // Instead it is returning both documents. ... }); 

我究竟做错了什么?

  • 按照WGS84标准定义位置时,我使用[long,lat]。
  • Runnings MongooseJS V3.8.8

问题是错误地使用maxDistance。 下面的expression式工作。

 Branch.geoNear({type: "Point", coordinates: [0.0776590, -33.7797590]}, { spherical: true, maxDistance: 1 / 6378137, distanceMultiplier: 6378137 }) .then(function (doc) { console.log(doc); process.exit(); }); Mongoose: branches.ensureIndex({ location: '2dsphere' }) { safe: undefined, background: true } Mongoose: branches.geoNear(0.077659) -33.779759 { distanceMultiplier: 6378137, lean: true, maxDistance: 1.567855942887398e-7, spherical: true } [] 

现在查询正确地发现集合中的两个文档不在查询位置的1米范围内。 查询离家较近的位置也给我们预期的结果。

 Branch.geoNear({type: "Point", coordinates: [153.027117, -27.468515]}, { spherical: true, maxDistance: 1 / 6378137, distanceMultiplier: 6378137 }) .then(function (doc) { console.log(doc); process.exit(); }); Mongoose: branches.ensureIndex({ location: '2dsphere' }) { safe: undefined, background: true } Mongoose: branches.geoNear(153.027117) -27.468515 { distanceMultiplier: 6378137, lean: true, maxDistance: 1.567855942887398e-7, spherical: true } [ { dis: 0.0026823704060803567, obj: { name: 'A', _id: 533200e49ba06bec37c0cc22, location: [Object], __v: 0 } } ] 

解决scheme?

geoNear的MongoDb文档指出,如果使用geoJSON对象,maxDistance应该以米为单位,如果使用坐标对,则以弧度单位。

可选的。 距离中心点的距离。 为GeoJSON数据指定以米为单位的距离,为旧有坐标对指定弧度。 MongoDB将结果限制为距中心点指定距离内的文档。 http://docs.mongodb.org/manual/reference/command/geoNear/#dbcmd.geoNear

这是错误的,或者我的理解是错误的。

正如你上面看到的,而不是指定1米为maxDistance,它是在Radians供应。

在这篇文章的date,geoNear要求无论你使用的是geoJSON对象还是传统的坐标对,maxDistance都是用Radians。

由于本地驱动程序的限制,Mongoose将geoJSON点转换为传统坐标对; 支持已经添加到本地驱动程序,并且有一个开放的公关将这个支持添加到Mongoose。 我更新了@NickB提供的问题。