node.js - 近场必须是点

标签 node.js mongodb mongoose aggregation-framework geojson

我正在使用 express 和 mongoose 构建一个 api。我有一个 Reviews 集合,它有一个存储 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 的使用不正确吗?非常感谢任何帮助!

最佳答案

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

所以改为将它们转换为整数或浮点值

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

关于node.js - 近场必须是点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507357/

相关文章:

javascript - Node crypto.randomBytes 从函数返回 token

node.js - 与 websocket 服务器库的 Passport session

javascript - 查找 mongo db 唯一文档

javascript - 如何返回一个对象与两个 Mongoose 模型相结合

javascript - GroupBy CSV 文件中的数组元素并有助于减少代码

mongodb - 坚持和冲洗 - Doctrine 和 MongoDB

java - MongoDB 从 BasicDBObject (Java) 中提取值

javascript - Mongoose/Nodejs 中的延迟加载/更多数据滚动

mongodb - Mongoose (mongodb)别名_id字段

javascript - 如何设置在 node.js 中运行异步函数的时间限制?