【问题标题】:Mongoose/MongoDB GeoJSON query gives back empty resultMongoose/MongoDB GeoJSON 查询返回空结果
【发布时间】:2021-07-22 14:30:27
【问题描述】:

我有一个包含此属性的架构(Tour)。 位置是 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)
   }
}

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

我做错了什么?

【问题讨论】:

标签: javascript angular typescript mongodb mongoose


【解决方案1】:

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

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,则以米为单位指定距离,如果指定点是旧坐标对,则以弧度为单位。

【讨论】:

  • 确实是距离...将距离缩放到 5000 最终对我有用!哇..谢谢:D
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2019-08-29
  • 2015-12-07
  • 2012-07-26
  • 1970-01-01
相关资源
最近更新 更多