mongodb-raw.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // do nothing if there is err connecting to db
  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. world._id = undefined; // remove _id from query response
  18. callback(err, world);
  19. });
  20. }
  21. function mongodbGetAllFortunes(callback) {
  22. collections.Fortune.find().toArray(function (err, fortunes) {
  23. callback(err, fortunes);
  24. })
  25. }
  26. function mongodbDriverUpdateQuery(callback) {
  27. collections.World.findAndModify({
  28. id: h.randomTfbNumber()
  29. }, [['_id','asc']], {
  30. $set: {randomNumber: h.randomTfbNumber()}
  31. }, {}, function (err, world) {
  32. world.value._id = undefined; // remove _id from query response
  33. callback(err, world.value);
  34. });
  35. }
  36. module.exports = {
  37. SingleQuery: function (req, res) {
  38. mongodbRandomWorld(function (err, result) {
  39. if (err) { return process.exit(1) }
  40. h.addTfbHeaders(res, 'json');
  41. res.end(JSON.stringify(result));
  42. });
  43. },
  44. MultipleQueries: function (queries, req, res) {
  45. var queryFunctions = h.fillArray(mongodbRandomWorld, queries);
  46. async.parallel(queryFunctions, function (err, results) {
  47. if (err) { return process.exit(1) }
  48. h.addTfbHeaders(res, 'json');
  49. res.end(JSON.stringify(results));
  50. });
  51. },
  52. Fortunes: function (req, res) {
  53. mongodbGetAllFortunes(function (err, fortunes) {
  54. if (err) { return process.exit(1) }
  55. fortunes.push(h.ADDITIONAL_FORTUNE);
  56. fortunes.sort(function (a, b) {
  57. return a.message.localeCompare(b.message);
  58. });
  59. h.addTfbHeaders(res, 'html');
  60. res.end(h.fortunesTemplate({
  61. fortunes: fortunes
  62. }));
  63. });
  64. },
  65. Updates: function (queries, req, res) {
  66. var queryFunctions = h.fillArray(mongodbDriverUpdateQuery, queries);
  67. async.parallel(queryFunctions, function (err, results) {
  68. if (err) { return process.exit(1) }
  69. h.addTfbHeaders(res, 'json');
  70. res.end(JSON.stringify(results));
  71. });
  72. }
  73. };