Mongoose/MongoDB GeoJSON 查询返回空结果

海德普宰

我有一个包含此属性的架构(游览)。该位置是 GeoJSON Point 类型。

location: {
      type: {
      type: String,
      enum: ['Point'],
      required: true
    },
    coordinates: {
      type: [Number],
      required: true
    },
    index: '2dsphere'
   },

我用于创建游览的控制器如下所示

const createTour = async (req, res) => {
   var newTour = new TourDB.Tour({
      ...
      location: { type: 'Point', coordinates: [req.body.tour.loc[0], req.body.tour.loc[1]] },
      ...
   })

   newTour.save(async (err, doc) => {
      if (!err) {
         return res.status(200).send(doc)
      } else {
         return res.status(500).send({ errorMessage: err })
      }
   })

在前端,我将使用此属性创建一个新的 Tour loc: [this.lng, this.lat],

这是 MongoDB 中的结果:

在此处输入图片说明

如何进行查询以获取半径内的位置?

我在我的控制器中尝试过这个(现在为了测试目的,radius 和 maxDistance 是硬编码的):

const getTourByRadius = async (req, res) =>  {
   let coords = [];
   coords[0] = 9.825031;
   coords[1] = 48.625107799999995

   const maxDistance = 10;

   try {
      const tour = await TourDB.Tour.find({
         location: {
            $near: {
               $geometry: {
                  type: "Point",
                  coordinates: coords
               },
               $maxDistance: maxDistance
            }
         }
      }).exec()
      res.send(tour)
   } catch (err) {
      res.send(err)
   }
}

但现在我得到一个空的 [] 回来。

我做错了什么?

沃恩弗里德·多姆沙伊特

你的距离是多少?一般来说,您的代码应该可以工作:

db.tour.insertOne({
   location: { type: 'Point', coordinates: [9.8238464, 47.627712] },
   cityName: "Geislingen"
})

db.tour.createIndex({ location: "2dsphere" })

let coords = [];
coords[0] = 9.825031;
coords[1] = 48.625107799999995

db.tour.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: coords },
        distanceField: "distance",
        spherical: true
     }
   }
])

返回:

{ 
    "_id" : ObjectId("608a73d51ef0d7c449c3e4c6"), 
    "location" : {
        "type" : "Point", 
        "coordinates" : [
            9.8238464, 
            48.627712
        ]
    }, 
    "cityName" : "Geislingen", 
    "distance" : 302.71595482740787
}

使用 maxDistance > 302.7 米返回文档:

let maxDistance = 303
db.tour.find(
   {
      location: {
         $near: {
            $geometry: { type: "Point", coordinates: coords },
            $maxDistance: 303
         }
      }
   }
)

{ 
    "_id" : ObjectId("608a73d51ef0d7c449c3e4c6"), 
    "location" : {
        "type" : "Point", 
        "coordinates" : [
            9.8238464, 
            48.627712
        ]
    }, 
    "cityName" : "Geislingen"
}

请注意,如果指定点是 GeoJSON,则以米为单位指定距离,如果指定点是旧坐标对,则以弧度指定距离。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章