You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB

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