geospatial.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // import async to make control flow simplier
  2. var async = require('async');
  3. // import the rest of the normal stuff
  4. var mongoose = require('../../lib');
  5. require('./person.js')();
  6. var Person = mongoose.model('Person');
  7. // define some dummy data
  8. var data = [
  9. { name : 'bill', age : 25, birthday : new Date().setFullYear((new
  10. Date().getFullYear() - 25)), gender : "Male",
  11. likes : ['movies', 'games', 'dogs'], loc : [0, 0]},
  12. { name : 'mary', age : 30, birthday : new Date().setFullYear((new
  13. Date().getFullYear() - 30)), gender : "Female",
  14. likes : ['movies', 'birds', 'cats'], loc : [1, 1]},
  15. { name : 'bob', age : 21, birthday : new Date().setFullYear((new
  16. Date().getFullYear() - 21)), gender : "Male",
  17. likes : ['tv', 'games', 'rabbits'], loc : [3, 3]},
  18. { name : 'lilly', age : 26, birthday : new Date().setFullYear((new
  19. Date().getFullYear() - 26)), gender : "Female",
  20. likes : ['books', 'cats', 'dogs'], loc : [6, 6]},
  21. { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
  22. Date().getFullYear() - 1000)), gender : "Male",
  23. likes : ['glasses', 'wine', 'the night'], loc : [10, 10]},
  24. ];
  25. mongoose.connect('mongodb://localhost/persons', function (err) {
  26. if (err) throw err;
  27. // create all of the dummy people
  28. async.each(data, function (item, cb) {
  29. Person.create(item, cb);
  30. }, function (err) {
  31. // let's find the closest person to bob
  32. Person.find({ name : 'bob' }, function (err, res) {
  33. if (err) throw err;
  34. res[0].findClosest(function (err, closest) {
  35. if (err) throw err;
  36. console.log("%s is closest to %s", res[0].name, closest);
  37. // we can also just query straight off of the model. For more
  38. // information about geospatial queries and indexes, see
  39. // http://docs.mongodb.org/manual/applications/geospatial-indexes/
  40. var coords = [7,7];
  41. Person.find({ loc : { $nearSphere : coords }}).limit(1).exec(function(err, res) {
  42. console.log("Closest to %s is %s", coords, res);
  43. cleanup();
  44. });
  45. });
  46. });
  47. });
  48. });
  49. function cleanup() {
  50. Person.remove(function() {
  51. mongoose.disconnect();
  52. });
  53. }