From 40cdb165f8747d4363294a33df00649bc3d51f95 Mon Sep 17 00:00:00 2001 From: Doguhan Okumus Date: Thu, 17 Jun 2021 20:33:54 +0300 Subject: [PATCH] .lean() with post-hook of .find and .findOne --- lib/mongoose-field-encryption.js | 54 +++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/lib/mongoose-field-encryption.js b/lib/mongoose-field-encryption.js index 40c6b4a..057f908 100644 --- a/lib/mongoose-field-encryption.js +++ b/lib/mongoose-field-encryption.js @@ -110,7 +110,13 @@ const fieldEncryption = function (schema, options) { } }; - function getCompatitibleNextFunc(next) { + function getCompatitibleNextFunc(next, data) { + // ! For the post-hook for .find and .findOne data is the first argument, + // ! therefore checking for an object in the first argument resolves the + // ! second argument to be next(). + if (typeof next === "object" && typeof data === "function") { + return data; + } if (typeof next !== "function") { return defaultNext; } @@ -122,6 +128,12 @@ const fieldEncryption = function (schema, options) { if (!data) { return next; } + // ! For the post-hook for .find and .findOne data is the first argument, + // ! therefore checking for an object in the first argument resolves the + // ! data. + if (typeof next === "object") { + return next; + } return data; } @@ -147,6 +159,13 @@ const fieldEncryption = function (schema, options) { } } + function decryptArrayFields(data, fields, secret) { + // ! looping through the array of data (multiple docs) + for (var obj of data) { + decryptFields(obj, fields, secret); + } + } + function decryptFields(obj, fields, secret) { for (const field of fields) { const encryptedFieldName = encryptedFieldNamePrefix + field; @@ -249,6 +268,39 @@ const fieldEncryption = function (schema, options) { } }); + schema.post('find', function (_next, _data) { + const next = getCompatitibleNextFunc(_next, _data); + const data = getCompatibleData(_next, _data); + // ! checking if the request has lean() + if (this._mongooseOptions.lean) { + try { + // ! Data is being returned as an array. We need to loop through them. + decryptArrayFields(data, fieldsToEncrypt, secret()); + next(); + } catch (err) { + next(err); + } + } else { + next(); + } + }) + + schema.post('findOne', function (_next, _data) { + const next = getCompatitibleNextFunc(_next, _data); + const data = getCompatibleData(_next, _data); + // ! checking if the request has lean() + if (this._mongooseOptions.lean) { + try { + decryptFields(data, fieldsToEncrypt, secret()); + next(); + } catch (err) { + next(err); + } + } else { + next(); + } + }) + schema.pre("findOneAndUpdate", updateHook); schema.pre("update", updateHook);