Yesterday evening, I was coding on my free-time project and dared touching some back-end code and a database schema.
I wanted to rename a key in a collection from created
to createdAt
, nothing complicated; Renaming a key in MongoDB normally is as simple as calling Schema.updateMany({}, { $rename: { oldKeyName: 'newKeyName' } })
, but for some reason it didn't work. After going through the docs, I found out this was not possible for that specific key name:
The
createdAt
property is immutable, and Mongoose overwrites any user-specified updates toupdatedAt
by default.
So I came up with another stupid idea: Just fetch all documents, delete them from the database, and insert them back in with the changed key name. This is the code I wrote for the operation: