尝试在Mongoose中使用$geoNear聚合,但收到错误消息:"Near字段必须是一个点"。

3
我正在使用Express和Mongoose构建一个API。我有一个Reviews集合,其中有一个存储geoJSON的location字段。我试图使用aggregate和$geoNear来查询我的Reviews集合。
这是我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时,我遇到了一个错误:
near字段必须是一个点
以下是带有查询的路由:
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))
});

我的查询语法是基于MongoDB的$geoNear文档。我在Mongoose中使用得正确吗?

2
尝试使用 parseFloat(req.params.longitude),同样适用于纬度。 - Ashh
@AnthonyWinzlet 谢谢你,Anthony!这解决了问题。 - nflauria
2个回答

3
问题出在坐标上,它们应该始终是数字,但你将其设为字符串。因此,应将它们转换为整数或浮点值。
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 - 如果您颠倒了它们或者只是指定了一个无效的坐标,则会收到相同的错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接