I also tried the following snippet to try to make the added getters/setters work:
for (const key of fieldsToEncrypt) {
SampleModel.schema.obj[key].set = encryptFunction;
SampleModel.schema.obj[key].get = decryptFunction;
}
SampleModel.schema.toObject = { getters: true, setters: true }
SampleModel.schema.toJSON = { getters: true, setters: true }
SampleModel.schema.runSettersOnQuery = true;
Unfortunately, it still didn’t work.
Also, I belatedly realized another problem which will still exist after fixing the problem above. I added a unique index in one of the fields to avoid inserting duplicate rows. If the value is to be encrypted now, the unique index will not be of use because the value inserted will be unique every time due to the random IV.