geoJSONexample.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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) throw err;
  18. Location.on('index', function(err) {
  19. if (err) throw err;
  20. // create all of the dummy locations
  21. async.each(data, function (item, cb) {
  22. Location.create(item, cb);
  23. }, function (err) {
  24. if (err) throw err;
  25. // create the location we want to search for
  26. var coords = { type : 'Point', coordinates : [-5, 5] };
  27. // search for it
  28. Location.find({ loc : { $near : coords }}).limit(1).exec(function(err, res) {
  29. if (err) throw err;
  30. console.log("Closest to %s is %s", JSON.stringify(coords), res);
  31. cleanup();
  32. });
  33. });
  34. });
  35. });
  36. function cleanup() {
  37. Location.remove(function() {
  38. mongoose.disconnect();
  39. });
  40. }