Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Geospatial Queries With Mongoose and Node.js

DZone's Guide to

Geospatial Queries With Mongoose and Node.js

· Database Zone
Free Resource

Traditional relational databases weren’t designed for today’s customers. Learn about the world’s first NoSQL Engagement Database purpose-built for the new era of customer experience.

 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!!!! :)

Learn how the world’s first NoSQL Engagement Database delivers unparalleled performance at any scale for customer experience innovation that never ends.

Topics:
java ,nosql ,tips and tricks ,query ,mongodb ,node.js ,geospatial

Published at DZone with permission of Will Soprano. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}