代码之家  ›  专栏  ›  技术社区  ›  nflauria

近场必须是点

  •  1
  • nflauria  · 技术社区  · 6 年前

    我正在使用Express和Mongoose构建API。我有一个评论集合,其中有一个存储geojson的位置字段。我正在尝试使用 骨料 元吉尔 .

    以下是我的reviewSchema中的相关部分:

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

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

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

    我可以使用 找到 近球体 :

    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))
    });
    

    尝试使用aggregate和$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文档。我在蒙古人身上使用这个错误吗?任何帮助都非常感谢!

    1 回复  |  直到 5 年前
        1
  •  1
  •   Ashh    5 年前

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

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

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