split_writefull_disabled_from_unset.js 1.5 KB

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