thoughts/node_modules/mongoose/examples/geospatial/geospatial.js
node_modules/mongoose/examples/geospatial/geospatial.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('./person.js')();
8
9var Person = mongoose.model('Person');
10
11// define some dummy data
12var data = [
13 {
14 name: 'bill',
15 age: 25,
16 birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
17 gender: 'Male',
18 likes: ['movies', 'games', 'dogs'],
19 loc: [0, 0]
20 },
21 {
22 name: 'mary',
23 age: 30,
24 birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
25 gender: 'Female',
26 likes: ['movies', 'birds', 'cats'],
27 loc: [1, 1]
28 },
29 {
30 name: 'bob',
31 age: 21,
32 birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
33 gender: 'Male',
34 likes: ['tv', 'games', 'rabbits'],
35 loc: [3, 3]
36 },
37 {
38 name: 'lilly',
39 age: 26,
40 birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
41 gender: 'Female',
42 likes: ['books', 'cats', 'dogs'],
43 loc: [6, 6]
44 },
45 {
46 name: 'alucard',
47 age: 1000,
48 birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
49 gender: 'Male',
50 likes: ['glasses', 'wine', 'the night'],
51 loc: [10, 10]
52 }
53];
54
55
56mongoose.connect('mongodb://localhost/persons', function(err) {
57 if (err) {
58 throw err;
59 }
60
61 // create all of the dummy people
62 async.each(data, function(item, cb) {
63 Person.create(item, cb);
64 }, function(err) {
65 if (err) {
66 // handler error
67 }
68
69 // let's find the closest person to bob
70 Person.find({name: 'bob'}, function(err, res) {
71 if (err) {
72 throw err;
73 }
74
75 res[0].findClosest(function(err, closest) {
76 if (err) {
77 throw err;
78 }
79
80 console.log('%s is closest to %s', res[0].name, closest);
81
82
83 // we can also just query straight off of the model. For more
84 // information about geospatial queries and indexes, see
85 // http://docs.mongodb.org/manual/applications/geospatial-indexes/
86 var coords = [7, 7];
87 Person.find({loc: {$nearSphere: coords}}).limit(1).exec(function(err, res) {
88 console.log('Closest to %s is %s', coords, res);
89 cleanup();
90 });
91 });
92 });
93 });
94});
95
96function cleanup() {
97 Person.remove(function() {
98 mongoose.disconnect();
99 });
100}