如何执行与Mongoose runCommand?
我正在使用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
谢谢,何塞
首先,直接使用geoNear和Mongoose(假设你想要读取计算的距离)还没有一个方便的包装器。
但是由于Mongoose集合代理了本地MongoDB本地驱动程序中的 所有收集方法 ,所以您可以使用它们的geoNear方法 ,尽pipe您必须放弃一些Mongoose的预期function,而在我的发现中,error handling有点不同。
无论如何,这是你如何使用这个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; } });
请参阅文档以获得正确的error handling以及如何计算距离 。
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,可以改变。
我不认为Mongoose现在支持runCommand
。 使用find
方法(例如>),最好使用地理空间选项
db.places.find( { location : { $near : [50,50] , $maxDistance : 300 } } )
希望这应该工作! 参考url: 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); });