Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Requires Node.js v6+ and a MongoDB library that supports promises (e.g. monk)
- /* EXAMPLE USAGE:
- const monk = require('monk');
- const dbUtils = require('./dbUtils.js');
- const db = monk('localhost:27017/monkey');
- const collection = db.get('contentItems');
- const newValue = 'WHATEVER';
- dbUtils.updateFieldInArrayOfObjects(db, collection, 'tracks', 'checked', newValue)
- .then(() => db.close())
- .catch(err => console.error(err));
- */
- // For all documents in a collection, that contain a field called arrayField,
- // which stores an array of objects, where objects in that array contain a field
- // called objectField - this function will update the value of objectField to newValue
- function updateFieldInArrayOfObjects(db, collection, arrayField, objectField, newValue) {
- return collection
- // Get all documents from collection
- .find({}, { [arrayField]: 1 })
- // Iterate each document
- .each(doc => {
- // Clone the arrayField array
- let arrayFieldClone = Array.from(doc[arrayField]);
- // Update all objectFields in arrayFieldClone with new value
- arrayFieldClone.forEach(item => item[objectField] = newValue);
- // Save arrayFieldClone to dB, replacing existing arrayField
- collection
- .update({ _id: doc._id }, { $set: { [arrayField]: arrayFieldClone } })
- .then(() => console.log(`Updated all ${arrayField}.${objectField} values to ${newValue} in doc ${doc._id}`));
- });
- }
- // Export the function for external use
- module.exports = {
- updateFieldInArrayOfObjects
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement