split_writefull_disabled_from_unset.mjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { db, waitForDb } 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. await waitForDb()
  25. // update all applicable user models
  26. await batchedUpdate(
  27. 'users',
  28. { 'writefull.enabled': false }, // and is false
  29. { $set: { 'writefull.enabled': null } }
  30. )
  31. const chunks = chunkArray(optedOutList, CHUNK_SIZE)
  32. // then reset any explicit false back to being false
  33. // Iterate over each chunk and perform the query
  34. for (const chunkedIds of chunks) {
  35. console.log('batch update started')
  36. await db.users.updateMany(
  37. { _id: { $in: chunkedIds } },
  38. { $set: { 'writefull.enabled': false } }
  39. )
  40. console.log('batch completed')
  41. }
  42. }
  43. export default main
  44. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  45. try {
  46. await main()
  47. process.exit(0)
  48. } catch (error) {
  49. console.error({ error })
  50. process.exit(1)
  51. }
  52. }