Last active
June 10, 2019 22:40
-
-
Save lukeaus/90f3a51ffead83e8b7a37de99904d824 to your computer and use it in GitHub Desktop.
Mongo rename embedded docs field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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