arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/mongoose/examples/querybuilder/querybuilder.js
node_modules/mongoose/examples/querybuilder/querybuilder.jsRaw
 1
 2// import async to make control flow simplier
 3var async = require('async');
 4
 5// import the rest of the normal stuff
 6var mongoose = require('../../lib');
 7
 8require('./person.js')();
 9
10var Person = mongoose.model('Person');
11
12// define some dummy data
13var 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
42mongoose.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
75function cleanup() {
76  Person.remove(function() {
77    mongoose.disconnect();
78  });
79}