20220913125500_migrate_auditLog_to_collections.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { batchedUpdate } from '@overleaf/mongo-utils/batchedUpdate.js'
  2. import { db } from './lib/mongodb.mjs'
  3. const tags = ['server-ce', 'server-pro', 'saas']
  4. const migrate = async () => {
  5. await batchedUpdate(
  6. db.users,
  7. { auditLog: { $exists: true } },
  8. async users => {
  9. await processUsersBatch(users)
  10. },
  11. { _id: 1, auditLog: 1 }
  12. )
  13. await batchedUpdate(
  14. db.projects,
  15. { auditLog: { $exists: true } },
  16. async projects => {
  17. await processProjectsBatch(projects)
  18. },
  19. { _id: 1, auditLog: 1 }
  20. )
  21. }
  22. async function processUsersBatch(users) {
  23. if (!users || users.length <= 0) {
  24. return
  25. }
  26. const entries = users
  27. .map(user => user.auditLog.map(log => ({ ...log, userId: user._id })))
  28. .flat()
  29. if (entries?.length > 0) {
  30. await db.userAuditLogEntries.insertMany(entries)
  31. }
  32. const userIds = users.map(user => user._id)
  33. await db.users.updateMany(
  34. { _id: { $in: userIds } },
  35. { $unset: { auditLog: 1 } }
  36. )
  37. }
  38. async function processProjectsBatch(projects) {
  39. if (!projects || projects.length <= 0) {
  40. return
  41. }
  42. const entries = projects
  43. .map(project =>
  44. project.auditLog.map(log => ({ ...log, projectId: project._id }))
  45. )
  46. .flat()
  47. if (entries?.length > 0) {
  48. await db.projectAuditLogEntries.insertMany(entries)
  49. }
  50. const projectIds = projects.map(project => project._id)
  51. await db.projects.updateMany(
  52. { _id: { $in: projectIds } },
  53. { $unset: { auditLog: 1 } }
  54. )
  55. }
  56. const rollback = async () => {}
  57. export default {
  58. tags,
  59. migrate,
  60. rollback,
  61. }