replica-sets.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // to connect to a replica set, pass in the comma delimited uri and optionally
  36. // any connection options such as the rs_name.
  37. var opts = {
  38. replSet: {rs_name: 'rs0'}
  39. };
  40. mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function(err) {
  41. if (err) throw err;
  42. // create all of the dummy people
  43. async.each(data, function(item, cb) {
  44. Person.create(item, cb);
  45. }, function(err) {
  46. if (err) {
  47. // handle error
  48. }
  49. // create and delete some data
  50. var prom = Person.find({age: {$lt: 1000}}).exec();
  51. prom.then(function(people) {
  52. console.log('young people: %s', people);
  53. }).then(cleanup);
  54. });
  55. });
  56. function cleanup() {
  57. Person.remove(function() {
  58. mongoose.disconnect();
  59. });
  60. }