fix_group_invite_emails_to_lowercase.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const DRY_RUN = process.env.DRY_RUN !== 'false'
  2. const { db, waitForDb } = require('../app/src/infrastructure/mongodb')
  3. const { batchedUpdate } = require('./helpers/batchedUpdate')
  4. console.log({
  5. DRY_RUN,
  6. })
  7. function anyInviteEmailHasUppercaseChars(subscription) {
  8. return subscription.teamInvites.some(invite => {
  9. return /[A-Z]/.test(invite.email)
  10. })
  11. }
  12. async function processBatch(subscriptions) {
  13. for (const subscription of subscriptions) {
  14. if (anyInviteEmailHasUppercaseChars(subscription)) {
  15. console.log('fixing emails in group invites for', subscription._id)
  16. if (!DRY_RUN) {
  17. await db.subscriptions.updateOne({ _id: subscription._id }, [
  18. {
  19. $set: {
  20. teamInvites: {
  21. $map: {
  22. input: '$teamInvites',
  23. in: {
  24. $mergeObjects: [
  25. '$$this',
  26. {
  27. email: {
  28. $toLower: '$$this.email',
  29. },
  30. },
  31. ],
  32. },
  33. },
  34. },
  35. },
  36. },
  37. ])
  38. }
  39. }
  40. }
  41. }
  42. async function main() {
  43. await waitForDb()
  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. main()
  56. .then(() => {
  57. console.error('Done.')
  58. process.exit(0)
  59. })
  60. .catch(error => {
  61. console.error({ error })
  62. process.exit(1)
  63. })