Skip to content

Instantly share code, notes, and snippets.

@quipu
Forked from chrisjhoughton/bootstrap.js
Created August 17, 2014 00:19
Show Gist options
  • Save quipu/90d446d81174d1b33e4c to your computer and use it in GitHub Desktop.
Save quipu/90d446d81174d1b33e4c to your computer and use it in GitHub Desktop.
GeoJSON queries using Mongo and SailsJS
module.exports.bootstrap = function (cb) {
// Ensure we have 2dsphere index on Property so GeoSpatial queries can work!
sails.models.YOURMODEL.native(function (err, collection) {
collection.ensureIndex({ coordinates: '2dsphere' }, function () {
// It's very important to trigger this callack method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
cb();
});
});
};
module.exports = {
attributes: {
coordinates: {
type: 'json'
}
},
/*
* Search models based on location
*/
search: function (conditions) {
// Let's build up a MongoDB query
var query = {};
// We need to use `native` for geo queries
Property.native(function (err, collection) {
// Co-ordinates are passed from the client side (GMaps JS API)
// Note that we don't get them server-side because apparently
// the server-side API isn't designed for real-time user searches.
// Probably too slow or something.
query.coordinates = {
$near: {
$geometry: {
type: "Point",
coordinates: [ // long then lat
conditions.coordinates.lng,
conditions.coordinates.lat
]
},
// $maxDistance : <distance in meters> // TODO
}
};
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment