How to execute runCommand with Mongoose?
I am using Node.js and Mongoose to access my MongoDB. I am using a model that stores some geo coordinates. I have them i开发者_开发问答ndexed and everything seems to work as expected. What I am trying to do is to retrieve the most near things from my request. On the MongoDB console I do something like this:
distances = db.runCommand({ geoNear : "deals", near : [11.252, 14.141], spherical : true, maxDistance : 300 }).results
However, I am not sure how to do this with Mongoose. Here is more information about the command I am trying to use: http://www.mongodb.org/display/DOCS/Geospatial+Indexing
Thanks, Jose
First of all there is not yet a convenience wrapper to use geoNear with Mongoose directly (given that you want to read the calculated distance).
But since Mongoose collections proxies all collection methods from the native MongoDB native driver you can just use their geoNear method, though you have to give up a little bit of convenience you might expect from Mongoose and in my findings the error handling was a little bit different.
Anyway, this is how you could use said 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;
}
});
Please refer to the docs for correct error handling and how to calculate the distances.
YourModel.db.db.executeDbCommand({geoNear : "locations", near : [11.252,14.141], spherical: true }, function(err,res) { console.log(res.documents[0].results)});
node 0.6.6, mongoose@2.4.9, mongodb version v2.0.2
its a bit hacky and could change.
I don't think Mongoose supports runCommand
right now. You would be better off using the geospatial options using the find
method e.g. >
db.places.find( { location : { $near : [50,50] , $maxDistance : 300 } } )
Hope this should work!! Referrence URL : http://mongoosejs.com/docs/api.html
// Legacy point
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);
});
精彩评论