mongoose.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Connects to MongoDB using the mongoose driver
  2. // Handles related routes
  3. var h = require('../helper');
  4. var Mongoose = require('mongoose');
  5. var async = require('async');
  6. var connection = Mongoose.connect('mongodb://127.0.0.1/hello_world');
  7. var WorldSchema = new Mongoose.Schema({
  8. id : Number,
  9. randomNumber: Number
  10. }, {
  11. collection: 'world'
  12. });
  13. var FortuneSchema = new Mongoose.Schema({
  14. id: Number,
  15. message: String
  16. }, {
  17. collection: 'fortune'
  18. });
  19. var Worlds = connection.model('World', WorldSchema);
  20. var Fortunes = connection.model('Fortune', FortuneSchema);
  21. function mongooseRandomWorld(callback) {
  22. Worlds.findOne({
  23. id: h.randomTfbNumber()
  24. }).exec(callback);
  25. }
  26. function mongooseGetAllFortunes(callback) {
  27. Fortunes.find({})
  28. .exec(callback);
  29. }
  30. module.exports = {
  31. SingleQuery: function(req, reply) {
  32. mongooseRandomWorld(function (err, world) {
  33. if (err) { return process.exit(1); }
  34. reply(world)
  35. .header('Server', 'hapi');
  36. });
  37. },
  38. MultipleQueries: function(req, reply) {
  39. var queries = h.getQueries(req);
  40. var worldsToGet = h.fillArray(mongooseRandomWorld, queries);
  41. async.parallel(worldsToGet, function (err, worlds) {
  42. if (err) { return process.exit(1); }
  43. reply(worlds)
  44. .header('Server', 'hapi');
  45. });
  46. },
  47. Fortunes: function(req, reply) {
  48. mongooseGetAllFortunes(function (err, fortunes) {
  49. if (err) { return process.exit(1); }
  50. fortunes.push(h.ADDITIONAL_FORTUNE);
  51. fortunes.sort(function (a, b) {
  52. return a.message.localeCompare(b.message);
  53. });
  54. reply.view('fortunes', {
  55. fortunes: fortunes
  56. })
  57. .header('Content-Type', 'text/html')
  58. .header('Server', 'hapi');
  59. });
  60. },
  61. Updates: function(req, reply) {
  62. var queries = h.getQueries(req);
  63. var worldsToGet = h.fillArray(mongooseRandomWorld, queries);
  64. async.parallel(worldsToGet, function (err, worlds) {
  65. if (err) { return process.exit(1); }
  66. var updateFunctions = []
  67. for (var i = 0; i < queries; i++) {
  68. (function (i) {
  69. updateFunctions.push(function (callback) {
  70. worlds[i].randomNumber = h.randomTfbNumber();
  71. Worlds.update({
  72. id: worlds[i].id
  73. }, {
  74. randomNumber: worlds[i].randomNumber
  75. }, callback);
  76. });
  77. }(i));
  78. }
  79. async.parallel(updateFunctions, function (err, results) {
  80. if (err) { return process.exit(1); }
  81. reply(worlds)
  82. .header('Server', 'hapi');
  83. });
  84. });
  85. }
  86. };