mongoose.js 1.8 KB

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