fix_group_invite_emails_to_lowercase.mjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { db, waitForDb } 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. await waitForDb()
  45. const projection = {
  46. _id: 1,
  47. teamInvites: 1,
  48. }
  49. const query = {
  50. 'teamInvites.0': {
  51. $exists: true,
  52. },
  53. }
  54. await batchedUpdate('subscriptions', query, processBatch, projection)
  55. }
  56. try {
  57. await main()
  58. console.error('Done.')
  59. process.exit(0)
  60. } catch (error) {
  61. console.error({ error })
  62. process.exit(1)
  63. }