split_writefull_disabled_from_unset.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { db } from '../app/src/infrastructure/mongodb.js'
  2. import BatchedUpdateModule from './helpers/batchedUpdate.mjs'
  3. import mongodb from 'mongodb-legacy'
  4. import fs from 'fs'
  5. import { fileURLToPath } from 'url'
  6. const { ObjectId } = mongodb
  7. const { batchedUpdate } = BatchedUpdateModule
  8. const CHUNK_SIZE = 1000
  9. // Function to chunk the array
  10. function chunkArray(array, size) {
  11. const result = []
  12. for (let i = 0; i < array.length; i += size) {
  13. result.push(array.slice(i, i + size))
  14. }
  15. return result
  16. }
  17. async function main() {
  18. // search for file of users who already explicitly opted out first
  19. const optOutPath = process.argv[2]
  20. const optedOutFile = fs.readFileSync(optOutPath, 'utf8')
  21. let optedOutList = optedOutFile
  22. optedOutList = optedOutFile.split('\n').map(id => new ObjectId(id))
  23. console.log(`preserving opt-outs of ${optedOutList.length} users`)
  24. // update all applicable user models
  25. await batchedUpdate(
  26. 'users',
  27. { 'writefull.enabled': false }, // and is false
  28. { $set: { 'writefull.enabled': null } }
  29. )
  30. const chunks = chunkArray(optedOutList, CHUNK_SIZE)
  31. // then reset any explicit false back to being false
  32. // Iterate over each chunk and perform the query
  33. for (const chunkedIds of chunks) {
  34. console.log('batch update started')
  35. await db.users.updateMany(
  36. { _id: { $in: chunkedIds } },
  37. { $set: { 'writefull.enabled': false } }
  38. )
  39. console.log('batch completed')
  40. }
  41. }
  42. export default main
  43. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  44. try {
  45. await main()
  46. process.exit(0)
  47. } catch (error) {
  48. console.error({ error })
  49. process.exit(1)
  50. }
  51. }