@@ -320,6 +320,16 @@ NativeConnection.prototype.createClient = async function createClient(uri, optio
320320 } ;
321321 }
322322
323+ const { schemaMap, encryptedFieldsMap } = this . _buildEncryptionSchemas ( ) ;
324+
325+ if ( Object . keys ( schemaMap ) . length > 0 ) {
326+ options . autoEncryption . schemaMap = schemaMap ;
327+ }
328+
329+ if ( Object . keys ( encryptedFieldsMap ) . length > 0 ) {
330+ options . autoEncryption . encryptedFieldsMap = encryptedFieldsMap ;
331+ }
332+
323333 this . readyState = STATES . connecting ;
324334 this . _connectionString = uri ;
325335
@@ -343,6 +353,55 @@ NativeConnection.prototype.createClient = async function createClient(uri, optio
343353 return this ;
344354} ;
345355
356+ /**
357+ * Given a connection, which may or may not have encrypted models, build
358+ * a schemaMap and/or an encryptedFieldsMap for the connection, combining all models
359+ * into a single schemaMap and encryptedFields map.
360+ *
361+ * @returns a copy of the options object with a schemaMap and/or an encryptedFieldsMap added to the options' autoEncryption
362+ * options.
363+ */
364+ NativeConnection . prototype . _buildEncryptionSchemas = function ( ) {
365+ const qeMappings = { } ;
366+ const csfleMappings = { } ;
367+
368+ // If discriminators are configured for the collection, there might be multiple models
369+ // pointing to the same namespace. For this scenario, we merge all the schemas for each namespace
370+ // into a single schema.
371+ // Notably, this doesn't allow for discriminators to declare multiple values on the same fields.
372+ for ( const model of Object . values ( this . models ) ) {
373+ const { schema, collection : { collectionName } } = model ;
374+ const namespace = `${ this . $dbName } .${ collectionName } ` ;
375+ if ( schema . encryptionType ( ) === 'csfle' ) {
376+ csfleMappings [ namespace ] ??= new Schema ( { } , { encryptionType : 'csfle' } ) ;
377+ csfleMappings [ namespace ] . add ( schema ) ;
378+ } else if ( schema . encryptionType ( ) === 'queryableEncryption' ) {
379+ qeMappings [ namespace ] ??= new Schema ( { } , { encryptionType : 'queryableEncryption' } ) ;
380+ qeMappings [ namespace ] . add ( schema ) ;
381+ }
382+ }
383+
384+ const schemaMap = Object . entries ( csfleMappings ) . reduce (
385+ ( schemaMap , [ namespace , schema ] ) => {
386+ schemaMap [ namespace ] = schema . _buildSchemaMap ( ) ;
387+ return schemaMap ;
388+ } ,
389+ { }
390+ ) ;
391+
392+ const encryptedFieldsMap = Object . entries ( qeMappings ) . reduce (
393+ ( encryptedFieldsMap , [ namespace , schema ] ) => {
394+ encryptedFieldsMap [ namespace ] = schema . _buildEncryptedFields ( ) ;
395+ return encryptedFieldsMap ;
396+ } ,
397+ { }
398+ ) ;
399+
400+ return {
401+ schemaMap, encryptedFieldsMap
402+ } ;
403+ } ;
404+
346405/*!
347406 * ignore
348407 */
0 commit comments