@@ -110,7 +110,13 @@ const fieldEncryption = function (schema, options) {
110110 }
111111 } ;
112112
113- function getCompatitibleNextFunc ( next ) {
113+ function getCompatitibleNextFunc ( next , data ) {
114+ // ! For the post-hook for .find and .findOne data is the first argument,
115+ // ! therefore checking for an object in the first argument resolves the
116+ // ! second argument to be next().
117+ if ( typeof next === "object" && typeof data === "function" ) {
118+ return data ;
119+ }
114120 if ( typeof next !== "function" ) {
115121 return defaultNext ;
116122 }
@@ -122,6 +128,12 @@ const fieldEncryption = function (schema, options) {
122128 if ( ! data ) {
123129 return next ;
124130 }
131+ // ! For the post-hook for .find and .findOne data is the first argument,
132+ // ! therefore checking for an object in the first argument resolves the
133+ // ! data.
134+ if ( typeof next === "object" ) {
135+ return next ;
136+ }
125137 return data ;
126138 }
127139
@@ -147,6 +159,13 @@ const fieldEncryption = function (schema, options) {
147159 }
148160 }
149161
162+ function decryptArrayFields ( data , fields , secret ) {
163+ // ! looping through the array of data (multiple docs)
164+ for ( var obj of data ) {
165+ decryptFields ( obj , fields , secret ) ;
166+ }
167+ }
168+
150169 function decryptFields ( obj , fields , secret ) {
151170 for ( const field of fields ) {
152171 const encryptedFieldName = encryptedFieldNamePrefix + field ;
@@ -249,6 +268,39 @@ const fieldEncryption = function (schema, options) {
249268 }
250269 } ) ;
251270
271+ schema . post ( 'find' , function ( _next , _data ) {
272+ const next = getCompatitibleNextFunc ( _next , _data ) ;
273+ const data = getCompatibleData ( _next , _data ) ;
274+ // ! checking if the request has lean()
275+ if ( this . _mongooseOptions . lean ) {
276+ try {
277+ // ! Data is being returned as an array. We need to loop through them.
278+ decryptArrayFields ( data , fieldsToEncrypt , secret ( ) ) ;
279+ next ( ) ;
280+ } catch ( err ) {
281+ next ( err ) ;
282+ }
283+ } else {
284+ next ( ) ;
285+ }
286+ } )
287+
288+ schema . post ( 'findOne' , function ( _next , _data ) {
289+ const next = getCompatitibleNextFunc ( _next , _data ) ;
290+ const data = getCompatibleData ( _next , _data ) ;
291+ // ! checking if the request has lean()
292+ if ( this . _mongooseOptions . lean ) {
293+ try {
294+ decryptFields ( data , fieldsToEncrypt , secret ( ) ) ;
295+ next ( ) ;
296+ } catch ( err ) {
297+ next ( err ) ;
298+ }
299+ } else {
300+ next ( ) ;
301+ }
302+ } )
303+
252304 schema . pre ( "findOneAndUpdate" , updateHook ) ;
253305
254306 schema . pre ( "update" , updateHook ) ;
0 commit comments