You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.4 KiB

  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('./geoJSONSchema.js')();
  6. var Location = mongoose.model('Location');
  7. // define some dummy data
  8. // note: the type can be Point, LineString, or Polygon
  9. var data = [
  10. {loc: {type: 'Point', coordinates: [-20.0, 5.0]}},
  11. {loc: {type: 'Point', coordinates: [6.0, 10.0]}},
  12. {loc: {type: 'Point', coordinates: [34.0, -50.0]}},
  13. {loc: {type: 'Point', coordinates: [-100.0, 70.0]}},
  14. {loc: {type: 'Point', coordinates: [38.0, 38.0]}}
  15. ];
  16. mongoose.connect('mongodb://localhost/locations', function(err) {
  17. if (err) {
  18. throw err;
  19. }
  20. Location.on('index', function(err) {
  21. if (err) {
  22. throw err;
  23. }
  24. // create all of the dummy locations
  25. async.each(data, function(item, cb) {
  26. Location.create(item, cb);
  27. }, function(err) {
  28. if (err) {
  29. throw err;
  30. }
  31. // create the location we want to search for
  32. var coords = {type: 'Point', coordinates: [-5, 5]};
  33. // search for it
  34. Location.find({loc: {$near: coords}}).limit(1).exec(function(err, res) {
  35. if (err) {
  36. throw err;
  37. }
  38. console.log('Closest to %s is %s', JSON.stringify(coords), res);
  39. cleanup();
  40. });
  41. });
  42. });
  43. });
  44. function cleanup() {
  45. Location.remove(function() {
  46. mongoose.disconnect();
  47. });
  48. }