6f8645b5eacaf52cda32feb65a9a1b2dd2958847
[aai/esr-gui.git] /
1
2 // import async to make control flow simplier
3 var async = require('async');
4
5 // import the rest of the normal stuff
6 var mongoose = require('../../lib');
7
8 require('./person.js')();
9
10 var Person = mongoose.model('Person');
11
12 // define some dummy data
13 var data = [
14   {
15     name: 'bill',
16     age: 25,
17     birthday: new Date().setFullYear((new Date().getFullYear() - 25))
18   },
19   {
20     name: 'mary',
21     age: 30,
22     birthday: new Date().setFullYear((new Date().getFullYear() - 30))
23   },
24   {
25     name: 'bob',
26     age: 21,
27     birthday: new Date().setFullYear((new Date().getFullYear() - 21))
28   },
29   {
30     name: 'lilly',
31     age: 26,
32     birthday: new Date().setFullYear((new Date().getFullYear() - 26))
33   },
34   {
35     name: 'alucard',
36     age: 1000,
37     birthday: new Date().setFullYear((new Date().getFullYear() - 1000))
38   }
39 ];
40
41
42 mongoose.connect('mongodb://localhost/persons', function(err) {
43   if (err) throw err;
44
45   // create all of the dummy people
46   async.each(data, function(item, cb) {
47     Person.create(item, cb);
48   }, function(err) {
49     if (err) throw err;
50
51     // when querying data, instead of providing a callback, you can instead
52     // leave that off and get a query object returned
53     var query = Person.find({age: {$lt: 1000}});
54
55     // this allows you to continue applying modifiers to it
56     query.sort('birthday');
57     query.select('name');
58
59     // you can chain them together as well
60     // a full list of methods can be found:
61     // http://mongoosejs.com/docs/api.html#query-js
62     query.where('age').gt(21);
63
64     // finally, when ready to execute the query, call the exec() function
65     query.exec(function(err, results) {
66       if (err) throw err;
67
68       console.log(results);
69
70       cleanup();
71     });
72   });
73 });
74
75 function cleanup() {
76   Person.remove(function() {
77     mongoose.disconnect();
78   });
79 }