mongodb-raw.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var h = require('../helper');
  2. var async = require('async')
  3. var MongoClient = require('mongodb').MongoClient;
  4. var collections = {
  5. World: null,
  6. Fortune: null
  7. };
  8. MongoClient.connect('mongodb://127.0.0.1/hello_world?maxPoolSize=5', function (err, db) {
  9. if (err) { throw err; }
  10. collections.World = db.collection('world');
  11. collections.Fortune = db.collection('fortune');
  12. });
  13. function mongodbRandomWorld(callback) {
  14. collections.World.findOne({
  15. id: h.randomTfbNumber()
  16. }, function (err, world) {
  17. if (err) { throw err; }
  18. world._id = undefined; // remove _id from query response
  19. callback(err, world);
  20. });
  21. }
  22. function mongodbGetAllFortunes(callback) {
  23. collections.Fortune.find().toArray(function (err, fortunes) {
  24. if (err) { throw err; }
  25. callback(err, fortunes);
  26. })
  27. }
  28. function mongodbDriverUpdateQuery(callback) {
  29. collections.World.findAndModify({
  30. id: h.randomTfbNumber()
  31. }, [['_id','asc']], {
  32. $set: {randomNumber: h.randomTfbNumber()}
  33. }, {}, function (err, world) {
  34. if (err) { throw err; }
  35. world.value._id = undefined; // remove _id from query response
  36. callback(err, world.value);
  37. });
  38. }
  39. module.exports = {
  40. SingleQuery: function (req, res) {
  41. mongodbRandomWorld(function (err, result) {
  42. if (err) { throw err; }
  43. h.addTfbHeaders(res, 'json');
  44. res.end(JSON.stringify(result));
  45. });
  46. },
  47. MultipleQueries: function (queries, req, res) {
  48. var queryFunctions = h.fillArray(mongodbRandomWorld, queries);
  49. async.parallel(queryFunctions, function (err, results) {
  50. if (err) { throw err; }
  51. h.addTfbHeaders(res, 'json');
  52. res.end(JSON.stringify(results));
  53. });
  54. },
  55. Fortunes: function (req, res) {
  56. mongodbGetAllFortunes(function (err, fortunes) {
  57. if (err) { throw err; }
  58. fortunes.push(h.ADDITIONAL_FORTUNE);
  59. fortunes.sort(function (a, b) {
  60. return a.message.localeCompare(b.message);
  61. });
  62. h.addTfbHeaders(res, 'html');
  63. res.end(h.fortunesTemplate({
  64. fortunes: fortunes
  65. }));
  66. });
  67. },
  68. Updates: function (queries, req, res) {
  69. var queryFunctions = h.fillArray(mongodbDriverUpdateQuery, queries);
  70. async.parallel(queryFunctions, function (err, results) {
  71. if (err) { throw err; }
  72. h.addTfbHeaders(res, 'json');
  73. res.end(JSON.stringify(results));
  74. });
  75. }
  76. };