查询mongoose mode.find near maxdistance不能返回正确的结果?

时间:2016-05-23 03:59:37

标签: node.js mongodb

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

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

1 个答案:

答案 0 :(得分:0)

试试这个

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/