尝试将聚合 $geoNear 与 Mongoose 一起使用,但收到错误:“近场必须是点”

问题描述 投票:0回答:2

我正在使用 Express 和 Mongoose 构建 API。我有一个评论集合,其中有一个存储 geoJSON 的位置字段。我正在尝试使用 aggregate$geoNear 查询我的评论集合。

这是我的 ReviewSchema 中的相关部分:

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

我还添加了一个2dsphere索引:

ReviewSchema.index({ location: '2dsphere' });

我能够使用 find$nearSphere 成功查询集合:

router.get('/:longitude/:latitude/:dist', (req, res) => {
  Review.find({
    location: {
     $nearSphere: {
       $geometry: {
         type: 'Point',
         coordinates: [req.params.longitude, req.params.latitude]
       },
       $maxDistance: req.params.dist * 1609.34
     }
   }
  })
  .then(reviews => res.json(reviews))
});

当尝试使用聚合和 $geoNear 但我收到错误:

近场必须是点

这是带有查询的路线:

router.get('/:longitude/:latitude', (req, res) => {
  Review.aggregate([{
     $geoNear: {
       near: {
         type: "Point",
         coordinates: [req.params.longitude, req.params.latitude]
       },
       spherical: true,
       maxDistance: 10 * 1609,
       distanceField: 'distance'
     }
   }])
   .then(reviews => res.json(reviews))
   .catch(err => console.log(err))
});

我的查询语法基于 $geoNear 的 MongoDB 文档。我是否错误地将它与 Mongoose 一起使用?

node.js mongodb mongoose aggregation-framework geojson
2个回答
3
投票

问题在于坐标始终应该是数字,而您将其设置为

String

因此将它们转换为整数或浮点值

Review.aggregate([{
  "$geoNear": {
    "near": {
      "type": "Point",
      "coordinates": [parseFloat(req.params.longitude), parseFloat(req.params.latitude)]
    },
    "spherical": true,
    "maxDistance": 10 * 1609,
    "distanceField": "distance"
  }
}])

0
投票

要添加到这个 - 地理坐标也必须有效,并且查询是 lng,lat - 如果你向后获取它们或简单地指定一个无效的坐标,那么你会得到相同的错误。

© www.soinside.com 2019 - 2024. All rights reserved.