Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. // Requires Node.js v6+ and a MongoDB library that supports promises (e.g. monk)
  2.  
  3. /* EXAMPLE USAGE:
  4. const monk = require('monk');
  5. const dbUtils = require('./dbUtils.js');
  6.  
  7. const db = monk('localhost:27017/monkey');
  8. const collection = db.get('contentItems');
  9. const newValue = 'WHATEVER';
  10.  
  11. dbUtils.updateFieldInArrayOfObjects(db, collection, 'tracks', 'checked', newValue)
  12. .then(() => db.close())
  13. .catch(err => console.error(err));
  14. */
  15.  
  16. // For all documents in a collection, that contain a field called arrayField,
  17. // which stores an array of objects, where objects in that array contain a field
  18. // called objectField - this function will update the value of objectField to newValue
  19. function updateFieldInArrayOfObjects(db, collection, arrayField, objectField, newValue) {
  20.  
  21. return collection
  22. // Get all documents from collection
  23. .find({}, { [arrayField]: 1 })
  24. // Iterate each document
  25. .each(doc => {
  26.  
  27. // Clone the arrayField array
  28. let arrayFieldClone = Array.from(doc[arrayField]);
  29.  
  30. // Update all objectFields in arrayFieldClone with new value
  31. arrayFieldClone.forEach(item => item[objectField] = newValue);
  32.  
  33. // Save arrayFieldClone to dB, replacing existing arrayField
  34. collection
  35. .update({ _id: doc._id }, { $set: { [arrayField]: arrayFieldClone } })
  36. .then(() => console.log(`Updated all ${arrayField}.${objectField} values to ${newValue} in doc ${doc._id}`));
  37. });
  38. }
  39.  
  40. // Export the function for external use
  41. module.exports = {
  42.  
  43. updateFieldInArrayOfObjects
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement