{"id":"2420213b26ff26ef","repo":"mongodb/node-mongodb-native","slug":"unable-to-complete-creating-data-keys-cause-mes","errorCode":null,"errorMessage":"Unable to complete creating data keys: ${cause.message}","messagePattern":"Unable to complete creating data keys: (.+?)","errorType":"exception","errorClass":"MongoCryptCreateDataKeyError","httpStatus":null,"severity":"error","filePath":"src/client-side-encryption/client_encryption.ts","lineNumber":621,"sourceCode":"              keyId: await this.createDataKey(provider, {\n                masterKey,\n                // clone the timeoutContext\n                // in order to avoid sharing the same timeout for server selection and connection checkout across different concurrent operations\n                timeoutContext: timeoutContext?.csotEnabled() ? timeoutContext?.clone() : undefined\n              })\n            }\n      );\n      const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises);\n\n      encryptedFields.fields = createDataKeyResolutions.map((resolution, index) =>\n        resolution.status === 'fulfilled' ? resolution.value : encryptedFields.fields[index]\n      );\n\n      const rejection = createDataKeyResolutions.find(\n        (result): result is PromiseRejectedResult => result.status === 'rejected'\n      );\n      if (rejection != null) {\n        throw new MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason });\n      }\n    }\n\n    try {\n      const collection = await db.createCollection<TSchema>(name, {\n        ...createCollectionOptions,\n        encryptedFields,\n        timeoutMS: timeoutContext?.csotEnabled()\n          ? timeoutContext?.getRemainingTimeMSOrThrow()\n          : undefined\n      });\n      return { collection, encryptedFields };\n    } catch (cause) {\n      throw new MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause });\n    }\n  }\n\n  /**","sourceCodeStart":603,"sourceCodeEnd":639,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/client-side-encryption/client_encryption.ts#L603-L639","documentation":"Thrown as MongoCryptCreateDataKeyError from ClientEncryption.createEncryptedCollection when one or more data-key creation promises reject. createEncryptedCollection creates a data key for each field in encryptedFields; if any of those creations fails (network, KMS, permissions), the aggregated rejection is re-thrown with this message. The original error is preserved in cause.","triggerScenarios":"Calling createEncryptedCollection with encryptedFields that list fields whose KMS provider is unreachable, whose masterKey is invalid, or whose key vault collection is not writable; transient network errors during key creation.","commonSituations":"Wrong/missing KMS credentials; key vault namespace on a read-only or non-existent database; AWS region/CMK ARN typo; firewall blocking KMS endpoint; concurrent runs that race on the same key vault.","solutions":["Inspect err.cause for the per-field rejection to identify which field and KMS provider failed.","Verify KMS connectivity and credentials for the configured provider (AWS/GCP/Azure/local).","Ensure the key vault namespace exists and the user has write access; pre-create keys with createDataKey to isolate the failure."],"exampleFix":"// before\ntry {\n  await ce.createEncryptedCollection(db, 'patients', { encryptedFields, provider: 'aws', createCollectionOptions });\n} catch (e) { /* opaque */ }\n\n// after\ntry {\n  await ce.createEncryptedCollection(db, 'patients', { encryptedFields, provider: 'aws', createCollectionOptions });\n} catch (e) {\n  console.error('field failures:', e.cause); // identify which field/KMS failed\n}","handlingStrategy":"try-catch","validationCode":"// Pre-flight: create one data key to validate KMS + key vault before bulk creation\nawait ce.createDataKey(provider, { masterKey }).catch(e => { throw new Error('KMS preflight failed: ' + e.message); });","typeGuard":"// Not applicable: KMS/permissions failure, not a type.","tryCatchPattern":"try {\n  await ce.createEncryptedCollection(db, name, opts);\n} catch (err) {\n  if (err.name === 'MongoCryptCreateDataKeyError') {\n    console.error('data key failure cause:', err.cause);\n    /* fix KMS creds/masterKey, then retry */\n  } else throw err;\n}","preventionTips":["Verify KMS credentials and network reachability before bulk operations.","Ensure the key vault namespace is writable.","Pre-create keys with createDataKey to isolate failures."],"tags":["csfle","client-encryption","data-keys","kms","createencryptedcollection"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}