migration.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* eslint-disable no-undef, no-var, vars-on-top, no-restricted-globals, regex/invalid, import/extensions */
  2. // ignore lint error because this file is js as mongoshell
  3. var pagesCollection = db.getCollection('pages');
  4. var revisionsCollection = db.getCollection('revisions');
  5. var getProcessorArray = require('./processor.js');
  6. var migrationType = process.env.MIGRATION_TYPE;
  7. var processors = getProcessorArray(migrationType);
  8. var operations = [];
  9. var batchSize = process.env.BATCH_SIZE ?? 100; // default 100 revisions in 1 bulkwrite
  10. var batchSizeInterval = process.env.BATCH_INTERVAL ?? 3000; // default 3 sec
  11. // ===========================================
  12. // replace method with processors
  13. // ===========================================
  14. function replaceLatestRevisions(body, processors) {
  15. var replacedBody = body;
  16. processors.forEach((processor) => {
  17. replacedBody = processor(replacedBody);
  18. });
  19. return replacedBody;
  20. }
  21. if (processors.length === 0) {
  22. throw Error('No valid processors found. Please enter a valid environment variable');
  23. }
  24. pagesCollection.find({}).forEach((doc) => {
  25. if (doc.revision) {
  26. var revision = revisionsCollection.findOne({ _id: doc.revision });
  27. var replacedBody = replaceLatestRevisions(revision.body, [...processors]);
  28. var operation = {
  29. updateOne: {
  30. filter: { _id: revision._id },
  31. update: {
  32. $set: { body: replacedBody },
  33. },
  34. },
  35. };
  36. operations.push(operation);
  37. // bulkWrite per 100 revisions
  38. if (operations.length > (batchSize - 1)) {
  39. revisionsCollection.bulkWrite(operations);
  40. // sleep time can be set from env var
  41. sleep(batchSizeInterval);
  42. operations = [];
  43. }
  44. }
  45. });
  46. revisionsCollection.bulkWrite(operations);
  47. print('migration complete!');