14

我正在使用 Node.js 和 Mongoose 来访问我的 MongoDB。我正在使用一个存储一些地理坐标的模型。我将它们编入索引,一切似乎都按预期工作。我想做的是从我的请求中检索最接近的东西。在 MongoDB 控制台上,我执行以下操作:

distances = db.runCommand({ geoNear : "deals", near : [11.252, 14.141], spherical : true, maxDistance : 300  }).results 

但是,我不确定如何使用 Mongoose 执行此操作。以下是有关我尝试使用的命令的更多信息:http ://www.mongodb.org/display/DOCS/Geospatial+Indexing

谢谢,何塞

4

4 回答 4

5

首先,目前还没有一个方便的包装器可以直接将 geoNear 与 Mongoose 一起使用(假设您想读取计算出的距离)。

但是由于 Mongoose 集合代理了来自本地MongoDB 本地驱动程序的所有集合方法,您可以只使用他们的geoNear 方法,尽管您必须放弃一些您可能期望从 Mongoose 获得的便利,并且在我的发现中,错误处理有点不同.

无论如何,这就是您可以使用上述 API 的方式:

YourModel.collection.geoNear(lon, lat, {spherical: true, maxDistance: d}, function(err, docs) {
  if (docs.results.length == 1) {
    var distance = docs.results[0].dis;
    var match = docs.results[0].obj;
  }
});

请参阅文档以了解正确的错误处理以及如何计算距离

于 2012-08-06T08:52:52.853 回答
1
YourModel.db.db.executeDbCommand({geoNear : "locations", near : [11.252,14.141], spherical: true }, function(err,res) { console.log(res.documents[0].results)});

节点 0.6.6,mongoose@2.4.9,mongodb 版本 v2.0.2

它有点hacky,可能会改变。

于 2012-01-16T13:09:23.570 回答
0

我不认为猫鼬runCommand现在支持。您最好使用以下find方法使用地理空间选项,例如 >

db.places.find( { location : { $near : [50,50] , $maxDistance : 300 } } )
于 2011-05-02T19:02:31.047 回答
0

希望这应该工作!参考网址: http ://mongoosejs.com/docs/api.html

// 遗留点

Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) {
   console.log(results);
});

//geoJson

var point = { type : "Point", coordinates : [9,9] };
Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
   console.log(results);
});
于 2016-11-28T12:38:40.483 回答