NoSQL Zone is brought to you in partnership with:

A tattooed digital marketer. I love baseball, the Braves, coffee, and innovative thinking. I can always be found on twitter or at a local ball field. Active & always smiling Will has posted 50 posts at DZone. You can read more from them at their website. View Full User Profile

Geospatial Queries with MongoDB and Node.js

09.04.2012
| 4735 views |
  • submit to reddit

 The following article was written by Javier Manzano

As I’m working on a new website on node.js with MongoDB (with mongoose), I’m just realizing how powerful is this combination. Just amazing.

In one of the new features I was developing I wanted to use geolocation on my searchs.

One of the first things you have to do is to tell mongoose (or MongoDB native driver) that one attribute is going to have a 2D index

var place = new Schema({
  ...
  creationDate: { type: Date, default: Date.now },
  userId: ObjectId,
  username: String,
  geo: {type: [Number], index: '2d'}
  ...
});
exports.PlaceService = mongoose.model('Place', place);

After that, we can include one method to find near places to the schema

place.methods.findNear = function(cb) {
  return this.model('Place').find({geo: { $nearSphere: this.geo, $maxDistance: 0.01} }, cb);
}

Now, if you’re using express.js, you can define a route in your app.js file (or whatever you call it and just add this function)

exports.nearPlaces = function(req, res) {
        //I'm just sending the geolocation points in a format like this 39.92,-23
        // but you can send it however you want
var coord = req.query.geo.split(',');
var Place = mongoose.model('Place');
var park = new Place({geo: coord});
place.findNear(
function(err,docs) {
if (!err) {
res.json(docs);
} else {
throw err;
}
});
};

As you can see, It’s incredible what you can achieve with just a bunch of lines of code.

I’m falling in love with Node.js!

See you later guys!!!! :)

Published at DZone with permission of its author, Will Soprano. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)