fix_group_invite_emails_to_lowercase.mjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { db } from '../app/src/infrastructure/mongodb.js'
  2. import BatchedUpdateModule from './helpers/batchedUpdate.mjs'
  3. const { batchedUpdate } = BatchedUpdateModule
  4. const DRY_RUN = process.env.DRY_RUN !== 'false'
  5. console.log({
  6. DRY_RUN,
  7. })
  8. function anyInviteEmailHasUppercaseChars(subscription) {
  9. return subscription.teamInvites.some(invite => {
  10. return /[A-Z]/.test(invite.email)
  11. })
  12. }
  13. async function processBatch(subscriptions) {
  14. for (const subscription of subscriptions) {
  15. if (anyInviteEmailHasUppercaseChars(subscription)) {
  16. console.log('fixing emails in group invites for', subscription._id)
  17. if (!DRY_RUN) {
  18. await db.subscriptions.updateOne({ _id: subscription._id }, [
  19. {
  20. $set: {
  21. teamInvites: {
  22. $map: {
  23. input: '$teamInvites',
  24. in: {
  25. $mergeObjects: [
  26. '$$this',
  27. {
  28. email: {
  29. $toLower: '$$this.email',
  30. },
  31. },
  32. ],
  33. },
  34. },
  35. },
  36. },
  37. },
  38. ])
  39. }
  40. }
  41. }
  42. }
  43. async function main() {
  44. const projection = {
  45. _id: 1,
  46. teamInvites: 1,
  47. }
  48. const query = {
  49. 'teamInvites.0': {
  50. $exists: true,
  51. },
  52. }
  53. await batchedUpdate('subscriptions', query, processBatch, projection)
  54. }
  55. try {
  56. await main()
  57. console.error('Done.')
  58. process.exit(0)
  59. } catch (error) {
  60. console.error({ error })
  61. process.exit(1)
  62. }