How to prevent changes on a field / On immutable indexes

So, I have an application in which there is a unique ID for every document. Changing it by mistake might be dangerous (as other collections are linked using said ID), but I wouldn’t store it in the _id field provided by MongoDB, just in case we realize it needs to be changed in the future.

Is there a way of preventing anyone to edit a field? Like creating an immutable index that can be deleted later if needed?
If not, what would be your approach for this?

Thanks in advance! :smile:

Hello @Ariel_Seisdedos,

Since, you have ruled out using _id field for this purpose, you can think about using Change Streams, which allow tracking changes on a collection’s data. The Change Events describe the fields updated for operationType: 'update' (relevant for your case). While this doesn’t stop anyone from changing a field value, you are sure to get notification of the update or change on a particular field.

Note that Change Streams feature usage requires that your MongoDB cluster is a replica-set or a sharded cluster.


In case you are using MongoDB NodeJS Driver and Mongoose ODM, there is a feature which allows defining a field as immutable. See SchemaType.prototype.immutable().

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.