mongoose.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. var h = require('../helper');
  2. var async = require('async');
  3. var Mongoose = require('mongoose');
  4. var connection = Mongoose.connect('mongodb://127.0.0.1/hello_world')
  5. // Mongoose Setup
  6. var WorldSchema = new Mongoose.Schema({
  7. id : Number,
  8. randomNumber: Number
  9. }, {
  10. collection: 'world'
  11. });
  12. var FortuneSchema = new Mongoose.Schema({
  13. id: Number,
  14. message: String
  15. }, {
  16. collection: 'fortune'
  17. });
  18. var Worlds = connection.model('World', WorldSchema);
  19. var Fortunes = connection.model('Fortune', FortuneSchema);
  20. function mongooseRandomWorld(callback) {
  21. Worlds.findOne({
  22. id: h.randomTfbNumber()
  23. }).exec(function (err, world) {
  24. callback(err, world);
  25. });
  26. }
  27. function mongooseGetAllFortunes(callback) {
  28. Fortunes.find({}).exec(function (err, fortunes) {
  29. callback(err, fortunes);
  30. });
  31. }
  32. module.exports = {
  33. SingleQuery: function (req, res) {
  34. mongooseRandomWorld(function (err, result) {
  35. if (err) { throw err; }
  36. h.addTfbHeaders(res, 'json');
  37. res.end(JSON.stringify(result));
  38. })
  39. },
  40. MultipleQueries: function (queries, req, res) {
  41. var queryFunctions = h.fillArray(mongooseRandomWorld, queries)
  42. async.parallel(queryFunctions, function (err, results) {
  43. if (err) { throw err; }
  44. h.addTfbHeaders(res, 'json');
  45. res.end(JSON.stringify(results));
  46. });
  47. },
  48. Fortunes: function (req, res) {
  49. mongooseGetAllFortunes(function (err, fortunes) {
  50. if (err) { throw err; }
  51. fortunes.push(h.ADDITIONAL_FORTUNE);
  52. fortunes.sort(function (a, b) {
  53. return a.message.localeCompare(b.message);
  54. });
  55. h.addTfbHeaders(res, 'html');
  56. res.end(h.fortunesTemplate({
  57. fortunes: fortunes
  58. }))
  59. });
  60. },
  61. Updates: function (queries, req, res) {
  62. var selectFunctions = h.fillArray(mongooseRandomWorld, queries);
  63. async.parallel(selectFunctions, function (err, worlds) {
  64. if (err) { throw err; }
  65. var updateFunctions = [];
  66. for (var i = 0; i < queries; i++) {
  67. (function (i) {
  68. updateFunctions.push(function (callback) {
  69. worlds[i].randomNumber = h.randomTfbNumber();
  70. Worlds.update({
  71. id: worlds[i].id
  72. }, {
  73. randomNumber: worlds[i].randomNumber
  74. }, callback);
  75. });
  76. })(i);
  77. }
  78. async.parallel(updateFunctions, function (err, results) {
  79. if (err) { throw err; }
  80. h.addTfbHeaders(res, 'json');
  81. // results does not have updated document information
  82. // if no err was found and thrown: all updates succeeded
  83. res.end(JSON.stringify(worlds));
  84. });
  85. });
  86. }
  87. };