migration21.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import async from "async";
  2. /**
  3. * Migration 21
  4. *
  5. * Migration for song ratings
  6. * @param {object} MigrationModule - the MigrationModule
  7. * @returns {Promise} - returns promise
  8. */
  9. export default async function migrate(MigrationModule) {
  10. const songModel = await MigrationModule.runJob("GET_MODEL", { modelName: "song" }, this);
  11. const playlistModel = await MigrationModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  12. const ratingsModel = await MigrationModule.runJob("GET_MODEL", { modelName: "ratings" }, this);
  13. return new Promise((resolve, reject) => {
  14. async.waterfall(
  15. [
  16. next => {
  17. this.log("INFO", `Migration 21. Finding songs with document version 8.`);
  18. songModel.find({ documentVersion: 8 }, { youtubeId: true }, next);
  19. },
  20. (songs, next) => {
  21. async.eachLimit(
  22. songs.map(song => song.youtubeId),
  23. 2,
  24. (youtubeId, next) => {
  25. async.waterfall(
  26. [
  27. next => {
  28. playlistModel.countDocuments(
  29. { songs: { $elemMatch: { youtubeId } }, type: "user-liked" },
  30. (err, likes) => {
  31. if (err) return next(err);
  32. return next(null, likes);
  33. }
  34. );
  35. },
  36. (likes, next) => {
  37. playlistModel.countDocuments(
  38. { songs: { $elemMatch: { youtubeId } }, type: "user-disliked" },
  39. (err, dislikes) => {
  40. if (err) return next(err);
  41. return next(err, { likes, dislikes });
  42. }
  43. );
  44. },
  45. ({ likes, dislikes }, next) => {
  46. ratingsModel.updateOne(
  47. { youtubeId },
  48. {
  49. $set: {
  50. likes,
  51. dislikes,
  52. documentVersion: 1
  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. }