Mongoose 使用 GeoJSON 点作为查询参数调用 geoNear 不起作用

2024-05-08

给定一个为包含 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 查询的行为不符合预期。我将此查询读为 “给定南美洲海岸附近的一个位置,搜索这些位置并找到距所提供位置 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]。
  • 跑步 MongooseJS V3.8.8

问题是错误地使用了 maxDistance。以下表达式有效。


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 } } ]

解决方案?

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

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

这要么是错误的,要么是我的理解是错误的。

正如您在上面看到的,maxDistance 不是指定 1 米,而是以弧度形式提供。

截至本文发布之日,geoNear 要求 maxDistance 为 弧度,无论您使用的是 geoJSON 对象还是 遗留坐标对。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongoose 使用 GeoJSON 点作为查询参数调用 geoNear 不起作用 的相关文章

随机推荐