【问题标题】:Query of mongoose mode.find near maxdistance not return correct results?mongoose mode.find near maxdistance 的查询不返回正确的结果?
【发布时间】:2016-05-23 15:38:25
【问题描述】:

我想对坐标进行地理搜索,我的代码如下:

location:{type:[Number],index: '2d'},

Shop.find({location:{$near:loc,$maxDistance: 5}}).limit(50).exec(function(err, doc) {
      if (err) {
        console.log(err);
      }

      callback(doc);
    });

我设置了 maxDistance: 5 这应该返回我在 5 公里内的点。但是实际返回的结果总是包含距离超过5km的点(甚至还有500km以上的点被返回)。

我该怎么办?

完整代码:

module.exports = function( mongoose) {
  var ShopSchema = new mongoose.Schema({
    shopName:     { type: String, unique: true },
    address:     { type: String},
    location:{type:[Number],index: '2d'},
    shopPicUrl:      {type: String},
    shopPicTrueUrl:{type: String},
    mark:  { type: String},
    open:{type:Boolean},
    shopType:{type:String},
    dish:   {type: [{
      dishName: { type: String},
      tags: { type: Array},
      price: { type: Number},
      intro: { type: String},
      dishPic:{ type: String},
      index:{type:Number}
    }]}

  });

  var Shop = mongoose.model('Shop', ShopSchema);

  var createShop = function(shopName, address,location, shopPicUrl, open,shopType,res, callback) {
    var shopInstance = new Shop({
      shopName: shopName,
      address: address,
      location: location,
      shopPicUrl: shopPicUrl,
      open:open,
      shopType:shopType
      //shopPicTrueUrl:shopPicTrueUrl
    });
    shopInstance.save(function(err){
      callback(err);
    });
  };
  return {
    createShop: createShop
  }
}

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    试试这个

    var calculatedMaxDistance = (5) / 6371; 
    /EARTHRADIUSIN KM
    
    
     Shop.find(
                 {
                    'geo': {
                              $near: [lat,long],
                              $maxDistance: calculatedMaxDistance
    
                            }
                  }
          )
    

    弧度计算参考这里https://docs.mongodb.org/manual/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes/

    【讨论】:

    • 我试过了,但计算出的MaxDistance 太小了,什么也没有返回。我猜 $maxDistance: 5 正好是 5 公里,我在 5 公里内得到结果。但也得到点 50 公里
    • (5/120) / 6371;让我们试试这个。
    • 你可以在这里粘贴你的商店架构吗?
    • 在你的架构“geo”中添加这个:[ lat, long ],
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多