mongoose.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Connects to MongoDB using the mongoose driver
  2. // Handles related routes
  3. const h = require('../helper');
  4. const Mongoose = require('mongoose');
  5. const connection = Mongoose.connect(
  6. 'mongodb://TFB-database/hello_world',
  7. { useMongoClient: true }
  8. );
  9. const WorldSchema = new Mongoose.Schema({
  10. id : Number,
  11. randomNumber: Number
  12. }, {
  13. collection: 'world'
  14. });
  15. const FortuneSchema = new Mongoose.Schema({
  16. id: Number,
  17. message: String
  18. }, {
  19. collection: 'fortune'
  20. });
  21. const Worlds = connection.model('World', WorldSchema);
  22. const Fortunes = connection.model('Fortune', FortuneSchema);
  23. const randomWorld = async () =>
  24. await Worlds.findOne({ id: h.randomTfbNumber() });
  25. const updateWorld = async (world) =>
  26. await Worlds.update(
  27. { id: world.randomNumber },
  28. { randomNumber: world.randomNumber }
  29. );
  30. module.exports = {
  31. SingleQuery: async (req, reply) => {
  32. reply(await randomWorld()).header('Server', 'hapi');
  33. },
  34. MultipleQueries: async (req, reply) => {
  35. const queries = h.getQueries(req);
  36. const results = h.fillArray(await randomWorld(), queries);
  37. reply(results).header('Server', 'hapi');
  38. },
  39. Fortunes: async (req, reply) => {
  40. const fortunes = await Fortunes.find({});
  41. fortunes.push(h.additionalFortune());
  42. fortunes.sort((a, b) => a.message.localeCompare(b.message));
  43. reply.view('fortunes', {
  44. fortunes: fortunes
  45. })
  46. .header('Content-Type', 'text/html')
  47. .header('Server', 'hapi');
  48. },
  49. Updates: async (req, reply) => {
  50. const queries = h.getQueries(req);
  51. const results = [];
  52. for (let i = 0; i < queries; i++) {
  53. const world = await randomWorld();
  54. world.randomNumber = h.randomTfbNumber();
  55. await updateWorld(world);
  56. results.push(world);
  57. }
  58. reply(results)
  59. .header('Content-Type', 'application/json')
  60. .header('Server', 'hapi');
  61. }
  62. };