【问题标题】:Mongoose grab a document for certain distance from a latitude-longitude coordinateMongoose 从经纬度坐标抓取文件一定距离
【发布时间】:2016-07-17 01:26:40
【问题描述】:

如果假设距离当前纬度/经度坐标 10 公里,我正在尝试在 Mongoose 中加载文档。

假设我有这个对象:

{
    lat: -33.9493992,
    lon: 151.1114885
}

在我的 Mongoose 数据库中,我有一个集合,这个集合中的每个文档也有保存 lat-lon 键。如何只抓取距给定坐标一定距离的条目?

例如,我只想抓取距离上述坐标最远 10 公里的文档。

我将不胜感激。

编辑: 我的代码:

初始化模型:

var schema = new mongoose.Schema({
title: String,
    title: String,
    coordinates: {
        type: [ Number ],
        default: [0, 0],
        index: '2dsphere'
    }
});

global.models.Point = mongoose.model('Point', schema);

以及试图在模型中找到的代码: router.route('/points/:lat/:lon') .get(函数 (req, res) { console.log('lat:' + req.params.lat + 'lon:' + req.params.lon);

        global.models.Point.find({
            coordinates: {
                $near: {
                    $maxDistance: 100 / 111.12,
                    $geometry: {
                        type: 'Point',
                        coordinates: [req.params.lon, req.params.lat]
                    }
                }
            }
        }, function (err, res) {
            if (err) {
                return console.log(err);
            }
            console.log(res);
        });
    }); 

存储在数据库集合中的对象:

{ 
    "_id" : ObjectId("56ea103eefedec96b6d4b203"), 
    "title" : "Some title", 
    "coordinates" : [
        5.2260167, 
        52.3500607
    ]
}

【问题讨论】:

  • 阅读文档。 $nearSphere。你不想要单独的属性。文档将告诉您文档应该如何存储数据。

标签: node.js mongodb mongoose odm


【解决方案1】:

在您的架构中,您需要定义如下字段:

location: { 
  type: [ Number ], 
  default: [ 0, 0 ], 
  index: '2dsphere' 
}

然后你可以像这样对它进行搜索操作:

Model.find({
  location: {
    $near: {
      $maxDistance: 100/111.12, // 100km
      $geometry: { 
        type: "Point", 
        coordinates: [151.1114885, -33.9493992] // [lon, lat]    
      }
    }
  }
}).exec(callback);

$maxDistance的解释说明:

1° latitude = 69.047 miles = 111.12 kilometers

【讨论】:

  • 您好,感谢您的回答。我是否需要使用 mongoose modelSchema 定义启动模型时定义的字段?我这样做了,结果是“未定义”......
  • 我得到一个空对象,我的 Schema 一定有问题。我将使用架构定义更新我的问题。我会很感激帮助。非常感谢奥列格。
  • @ArielWeinberger 坐标应该是一个数组字段,而不是一个对象。请再检查一次我的答案
  • 嘿。实际上我忘了编辑,但我确实像你一样将它用作数组,但结果我仍然得到一个空数组:(
  • 我还编辑并添加了文档,因为它存储在集合中,也许我在那里做错了什么......
猜你喜欢
  • 2014-12-16
  • 1970-01-01
  • 2016-02-03
  • 2010-12-13
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多