migration21.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. documentVersion: 1
  54. }
  55. },
  56. { upsert: true },
  57. next
  58. );
  59. }
  60. ],
  61. next
  62. );
  63. },
  64. err => {
  65. next(err);
  66. }
  67. );
  68. },
  69. next => {
  70. songModel.updateMany(
  71. { documentVersion: 8 },
  72. {
  73. $set: { documentVersion: 9 },
  74. $unset: { likes: true, dislikes: true }
  75. },
  76. (err, res) => {
  77. if (err) next(err);
  78. else {
  79. this.log(
  80. "INFO",
  81. `Migration 21 (songs). Matched: ${res.matchedCount}, modified: ${res.modifiedCount}, ok: ${res.ok}.`
  82. );
  83. next();
  84. }
  85. }
  86. );
  87. }
  88. ],
  89. err => {
  90. if (err) reject(new Error(err));
  91. else resolve();
  92. }
  93. );
  94. });
  95. }