Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. module.exports = function() {
  2. const Workout = require('../../app/models/workout');
  3. const fs = require('fs');
  4.  
  5. require('../../app/models/level');
  6. require('../../app/models/topic');
  7. require('../../app/models/subtopic');
  8.  
  9. const getWorkoutTitle = function(workout) {
  10. return workout.title || workout.topic.name + ' ' + workout.subtopic.name + ' ' + workout.level.label;
  11. }
  12.  
  13. const encodeWorkoutsIds = function(workout) {
  14. return workout.insights.map(i => i.toString()).join('+');
  15. }
  16.  
  17. const workoutsList = {};
  18. const query = {
  19. hardcoded: true,
  20. done: true,
  21. userRating: { $exists: true },
  22. topic: { $exists: true },
  23. subtopic: { $exists: true },
  24. level: { $exists: true },
  25. };
  26.  
  27. let counter = 0;
  28.  
  29. Workout.count(query).then(totalWorkoutsCount => {
  30. const workoutStream = Workout.find(query, {
  31. title: 1,
  32. insights: 1,
  33. userRating: 1,
  34. topic: 1,
  35. subtopic: 1,
  36. level: 1
  37. }).populate('topic','name').populate('subtopic','name').populate('level', 'label')
  38. .limit(30).lean().stream();
  39.  
  40. workoutStream.on('data', workout => {
  41. workoutStream.pause();
  42.  
  43. const encoded = encodeWorkoutsIds(workout);
  44. if(!workoutsList[encoded]) {
  45. workoutsList[encoded] = {
  46. title: getWorkoutTitle(workout),
  47. insights: workout.insights.map(i => i.toString()),
  48. avg: workout.userRating,
  49. count: 1,
  50. sum: workout.userRating,
  51. topic: workout.topic.name,
  52. subtopics: workout.subtopic.name,
  53. level: workout.level.label,
  54. }
  55. } else {
  56. workoutsList[encoded].count += 1;
  57. workoutsList[encoded].sum += workout.userRating;
  58. workoutsList[encoded].avg = workoutsList[encoded].sum /
  59. workoutsList[encoded].count;
  60. }
  61.  
  62. counter += 1;
  63. console.log(counter + '/' + totalWorkoutsCount);
  64. workoutStream.resume();
  65. });
  66.  
  67.  
  68. workoutStream.on('end', () => {
  69. console.log('done');
  70. // console.log(workoutsList);
  71. fs.writeFile('output.txt', JSON.stringify(workoutsList, null, 2), err => {
  72. if (err) console.log('something wrong happened', err);
  73. console.log('done writing to file');
  74. process.exit(0);
  75. })
  76. });
  77.  
  78. workoutStream.on('error', err =>{
  79. console.log(err);
  80. process.exit(1);
  81. });
  82.  
  83. });
  84. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement