thoughts/node_modules/mongoose/examples/geospatial/geoJSONexample.js
node_modules/mongoose/examples/geospatial/geoJSONexample.jsRaw
1// import async to make control flow simplier
2var async = require('async');
3
4// import the rest of the normal stuff
5var mongoose = require('../../lib');
6
7require('./geoJSONSchema.js')();
8
9var Location = mongoose.model('Location');
10
11// define some dummy data
12// note: the type can be Point, LineString, or Polygon
13var data = [
14 {loc: {type: 'Point', coordinates: [-20.0, 5.0]}},
15 {loc: {type: 'Point', coordinates: [6.0, 10.0]}},
16 {loc: {type: 'Point', coordinates: [34.0, -50.0]}},
17 {loc: {type: 'Point', coordinates: [-100.0, 70.0]}},
18 {loc: {type: 'Point', coordinates: [38.0, 38.0]}}
19];
20
21
22mongoose.connect('mongodb://localhost/locations', function(err) {
23 if (err) {
24 throw err;
25 }
26
27 Location.on('index', function(err) {
28 if (err) {
29 throw err;
30 }
31 // create all of the dummy locations
32 async.each(data, function(item, cb) {
33 Location.create(item, cb);
34 }, function(err) {
35 if (err) {
36 throw err;
37 }
38 // create the location we want to search for
39 var coords = {type: 'Point', coordinates: [-5, 5]};
40 // search for it
41 Location.find({loc: {$near: coords}}).limit(1).exec(function(err, res) {
42 if (err) {
43 throw err;
44 }
45 console.log('Closest to %s is %s', JSON.stringify(coords), res);
46 cleanup();
47 });
48 });
49 });
50});
51
52function cleanup() {
53 Location.remove(function() {
54 mongoose.disconnect();
55 });
56}