Skip to content

Instantly share code, notes, and snippets.

@stdarg
Created October 5, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stdarg/26aaded1cf7dc5f404d2 to your computer and use it in GitHub Desktop.
Save stdarg/26aaded1cf7dc5f404d2 to your computer and use it in GitHub Desktop.
var MongoClient = require('mongodb').MongoClient;
var async = require('async');
var collection;
var db;
var resultsLimit = 2;
async.series([
// open connection to local MongoDB server
function(cb) {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db_in) {
if (err) return cb(err);
db = db_in;
return cb();
});
},
// add a list of items with coordinates
function(cb) {
collection = db.collection('geo_test');
cb();
},
// create a geospatial index
function(cb) {
collection.createIndex({ loc : '2dsphere' }, function(err) {
if (err) {
console.error(err.stack);
return cb(err);
}
return cb();
});
},
// add items into the collection
function(cb) {
addItems(cb);
},
// find all items in the collection, within 5 miles of my location
// at The Beacon
function(cb) {
// Note: here the coordinates are [ longitude, latitude ]
var qry = {
loc: {
$near: {
$geometry: {
type: 'Point',
coordinates: [-122.393868, 37.777151]
},
$maxDistance: 8046.72
}
}
};
collection.find(qry, {limit: resultsLimit}).toArray(function(err, results) {
if (err) return cb(err);
return cb(null, results);
});
},
// drop the collection (delete it)
function(cb) {
collection.drop(function(err) {
if (err) return cb(err);
return cb();
});
}],
// completion function & error handler
function(err, results) {
db.close();
if (err) {
console.error(err.stack);
return;
}
// 4th index is where the query results are
for (var i=0; i<results[4].length; i++) {
console.log(i+1, results[4][i].name);
}
}
);
function setObj(obj) {
obj.loc = { type: 'Point', coordinates: [ obj.lon, obj.lat ] };
delete obj.lat;
delete obj.lon;
return obj;
}
// I know MongoDB is async and coordination is not needed, but ...
// I like known when all methods had an async cb triggered.
function addItems(cb) {
async.map([
{ lat: 37.777151, lon: -122.393868, name: 'The Beacon'},
{ lat: 37.790130, lon: -122.394781, name: '199 Fremont'},
{ lat: 37.795743, lon: -122.393622, name: 'The Ferry Building'},
{ lat: 37.803220, lon: -122.257826, name: 'Lake Merit, Oakland'},
{ lat: 37.331555, lon: -121.887166, name: 'San Jose Tech Museum'},
{ lat: 36.964301, lon: -122.018511, name: 'Santa Cruz Boardwalk'},
],
// iterator
function (item, cb) {
var obj = setObj(item);
collection.insert(obj, function(err, docs) {
return cb(err, docs);
});
},
function(err) {
if (err) {
console.error(err.stack);
collection.drop(function(err) {
if (err) return cb(err);
return cb();
});
return;
}
return cb();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment