Skip to content

Instantly share code, notes, and snippets.

@lukeaus
Last active June 10, 2019 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukeaus/90f3a51ffead83e8b7a37de99904d824 to your computer and use it in GitHub Desktop.
Save lukeaus/90f3a51ffead83e8b7a37de99904d824 to your computer and use it in GitHub Desktop.
Mongo rename embedded docs field
/*
* Given the following schema for collection 'foo':
* myDoc: {
* embeddedDocs: [
* {
* bar: 'a',
* baz: 'b',
* },
* {
* bar: 'b',
* baz: 'b',
* },
* ]
* }
*
* Renames the following fields:
* 'bar' --> 'kar'
* 'baz' --> 'kaz'
*
* @param {object} db Your database
* @param {string} collectionName Your collection name e.g. 'foo'
* @param {string} embeddedDocumentsFieldName e.g. 'embeddedDocs'
* @param {array} fields Fields that you want to rename
* [{ oldField: 'bar', newField: 'kar' }, { oldField: 'baz', newField: 'kaz' }];
* @return {undefined}
*/
module.exports = (db, collectionName, embeddedDocumentsFieldName, fields) => {
const findKey = `${embeddedDocumentsFieldName}.0`;
db.collection(collectionName)
.find({
[findKey]: {$exists: true}, // check > 0 subdocuments
})
.snapshot() // https://stackoverflow.com/a/26050901/3003438
.forEach(doc => {
doc[embeddedDocumentsFieldName].forEach(embeddedDocument => {
fields.map(({oldField, newField}) => {
if (oldField in embeddedDocument) {
embeddedDocument[newField] = embeddedDocument[oldField];
try {
Reflect.deleteProperty(embeddedDocument, oldField);
} catch (err) {
if (err instanceof TypeError) {
delete embeddedDocument[
oldField
]; /* eslint prefer-reflect : 0 */
} else {
throw err;
}
}
db.collection(collectionName).update({_id: doc._id}, doc);
}
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment