migration21.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import async from "async";
  2. /**
  3. * Migration 21
  4. *
  5. * Migration for song ratings
  6. *
  7. * @param {object} MigrationModule - the MigrationModule
  8. * @returns {Promise} - returns promise
  9. */
  10. export default async function migrate(MigrationModule) {
  11. const songModel = await MigrationModule.runJob("GET_MODEL", { modelName: "song" }, this);
  12. const playlistModel = await MigrationModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  13. const ratingsModel = await MigrationModule.runJob("GET_MODEL", { modelName: "ratings" }, this);
  14. return new Promise((resolve, reject) => {
  15. async.waterfall(
  16. [
  17. next => {
  18. this.log("INFO", `Migration 21. Finding songs with document version 8.`);
  19. songModel.find({ documentVersion: 8 }, { youtubeId: true }, next);
  20. },
  21. (songs, next) => {
  22. async.eachLimit(
  23. songs.map(song => song.youtubeId),
  24. 2,
  25. (youtubeId, next) => {
  26. async.waterfall(
  27. [
  28. next => {
  29. playlistModel.countDocuments(
  30. { songs: { $elemMatch: { youtubeId } }, type: "user-liked" },
  31. (err, likes) => {
  32. if (err) return next(err);
  33. return next(null, likes);
  34. }
  35. );
  36. },
  37. (likes, next) => {
  38. playlistModel.countDocuments(
  39. { songs: { $elemMatch: { youtubeId } }, type: "user-disliked" },
  40. (err, dislikes) => {
  41. if (err) return next(err);
  42. return next(err, { likes, dislikes });
  43. }
  44. );
  45. },
  46. ({ likes, dislikes }, next) => {
  47. ratingsModel.updateOne(
  48. { youtubeId },
  49. {
  50. $set: {
  51. likes,
  52. dislikes
  53. }
  54. },
  55. { upsert: true },
  56. next
  57. );
  58. }
  59. ],
  60. next
  61. );
  62. },
  63. err => {
  64. next(err);
  65. }
  66. );
  67. },
  68. next => {
  69. songModel.updateMany(
  70. { documentVersion: 8 },
  71. {
  72. $set: { documentVersion: 9 },
  73. $unset: { likes: true, dislikes: true }
  74. },
  75. (err, res) => {
  76. if (err) next(err);
  77. else {
  78. this.log(
  79. "INFO",
  80. `Migration 21 (songs). Matched: ${res.matchedCount}, modified: ${res.modifiedCount}, ok: ${res.ok}.`
  81. );
  82. next();
  83. }
  84. }
  85. );
  86. }
  87. ],
  88. err => {
  89. if (err) reject(new Error(err));
  90. else resolve();
  91. }
  92. );
  93. });
  94. }