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.

94 lines
2.3 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) {
  37. throw err;
  38. }
  39. // create all of the dummy people
  40. async.each(data, function(item, cb) {
  41. Person.create(item, cb);
  42. }, function(err) {
  43. if (err) {
  44. // handle error
  45. }
  46. // create a promise (get one from the query builder)
  47. var prom = Person.find({age: {$lt: 1000}}).exec();
  48. // add a callback on the promise. This will be called on both error and
  49. // complete
  50. prom.addBack(function() {
  51. console.log('completed');
  52. });
  53. // add a callback that is only called on complete (success) events
  54. prom.addCallback(function() {
  55. console.log('Successful Completion!');
  56. });
  57. // add a callback that is only called on err (rejected) events
  58. prom.addErrback(function() {
  59. console.log('Fail Boat');
  60. });
  61. // you can chain things just like in the promise/A+ spec
  62. // note: each then() is returning a new promise, so the above methods
  63. // that we defined will all fire after the initial promise is fulfilled
  64. prom.then(function(people) {
  65. // just getting the stuff for the next query
  66. var ids = people.map(function(p) {
  67. return p._id;
  68. });
  69. // return the next promise
  70. return Person.find({_id: {$nin: ids}}).exec();
  71. }).then(function(oldest) {
  72. console.log('Oldest person is: %s', oldest);
  73. }).then(cleanup);
  74. });
  75. });
  76. function cleanup() {
  77. Person.remove(function() {
  78. mongoose.disconnect();
  79. });
  80. }