batchedUpdate.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const { promisify } = require('util')
  2. const { ReadPreference, ObjectId } = require('mongodb')
  3. const { getNativeDb } = require('../../app/src/infrastructure/Mongoose')
  4. const BATCH_SIZE = parseInt(process.env.BATCH_SIZE, 10) || 1000
  5. let BATCH_LAST_ID
  6. if (process.env.BATCH_LAST_ID) {
  7. BATCH_LAST_ID = ObjectId(process.env.BATCH_LAST_ID)
  8. }
  9. async function getNextBatch(collection, query, maxId) {
  10. if (maxId) {
  11. query['_id'] = { $gt: maxId }
  12. }
  13. const entries = await collection
  14. .find(query, { _id: 1 })
  15. .sort({ _id: 1 })
  16. .limit(BATCH_SIZE)
  17. .setReadPreference(ReadPreference.SECONDARY)
  18. .toArray()
  19. return entries.map(entry => entry._id)
  20. }
  21. async function performUpdate(collection, nextBatch, update) {
  22. return collection.updateMany({ _id: { $in: nextBatch } }, update)
  23. }
  24. async function batchedUpdate(collectionName, query, update) {
  25. // Apparently the mongo driver returns the connection too early.
  26. // Some secondary connections are not ready as it returns, leading to
  27. // failing cursor actions with a readPreference set to 'secondary'.
  28. // TODO(das7pad): revisit/remove this delay after the mongo-driver update.
  29. await Promise.all([getNativeDb(), promisify(setTimeout)(10 * 1000)])
  30. const db = await getNativeDb()
  31. const collection = db.collection(collectionName)
  32. let nextBatch
  33. let updated = 0
  34. let maxId = BATCH_LAST_ID
  35. while ((nextBatch = await getNextBatch(collection, query, maxId)).length) {
  36. maxId = nextBatch[nextBatch.length - 1]
  37. updated += nextBatch.length
  38. console.log(JSON.stringify(nextBatch))
  39. await performUpdate(collection, nextBatch, update)
  40. }
  41. return updated
  42. }
  43. function batchedUpdateWithResultHandling(collection, query, update) {
  44. batchedUpdate(collection, query, update)
  45. .then(updated => {
  46. console.error({ updated })
  47. process.exit(0)
  48. })
  49. .catch(error => {
  50. console.error({ error })
  51. process.exit(1)
  52. })
  53. }
  54. module.exports = {
  55. batchedUpdate,
  56. batchedUpdateWithResultHandling
  57. }