mongodb/node-mongodb-native · error · MongoCryptCreateDataKeyError

Unable to complete creating data keys

Error message

Unable to complete creating data keys: ${cause.message}

What it means

Thrown by ClientEncryption.createEncryptedCollection() when one or more createDataKey() calls fail during the collection creation process. This method creates data keys for encryptedFields that lack a keyId, then creates the collection. If data key creation fails partway through, this error includes the partial encryptedFields that were successfully generated. This is a MongoCryptCreateDataKeyError.

Solutions

  1. Check the error.cause for the specific failure reason (KMS error, network error, etc.)
  2. Verify KMS provider connectivity and credentials before calling createEncryptedCollection
  3. Ensure the key vault collection exists and is writable
  4. The error.encryptedFields property contains partially generated fields; inspect it to understand which keys succeeded
Defensive patterns

Strategy: try-catch

Validate before calling

// Before calling createEncryptedCollection, verify KMS connectivity
// Test KMS credentials by creating a test data key first
try {
  await clientEncryption.createDataKey(provider, { masterKey });
} catch (e) {
  console.error('KMS connectivity test failed:', e.message);
}

Try / catch

try {
  const result = await clientEncryption.createEncryptedCollection(db, name, options);
} catch (error) {
  if (error instanceof MongoCryptCreateDataKeyError) {
    // Data key creation failed; error.encryptedFields has partial results
    console.error('Failed to create data keys:', error.cause?.message);
    console.error('Partial encryptedFields:', error.encryptedFields);
    // Fix KMS connectivity and retry
  }
}

Prevention

When it happens

Trigger: Calling createEncryptedCollection() with encryptedFields containing fields that need new data keys, but the KMS provider is unreachable, credentials are invalid, or the key vault collection has issues. The error's cause property contains the underlying rejection reason.

Common situations: KMS connectivity issues (AWS, Azure, GCP unreachable); invalid KMS credentials; the key vault MongoDB collection does not exist or is not writable; network partitions during key creation; concurrent calls to createEncryptedCollection for the same fields.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@dce7939f86 (2026-08-11). Data as JSON: /api/errors/2420213b26ff26ef. Report an issue: GitHub.

Appendix: source

Thrown at src/client-side-encryption/client_encryption.ts:621

              keyId: await this.createDataKey(provider, {
                masterKey,
                // clone the timeoutContext
                // in order to avoid sharing the same timeout for server selection and connection checkout across different concurrent operations
                timeoutContext: timeoutContext?.csotEnabled() ? timeoutContext?.clone() : undefined
              })
            }
      );
      const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises);

      encryptedFields.fields = createDataKeyResolutions.map((resolution, index) =>
        resolution.status === 'fulfilled' ? resolution.value : encryptedFields.fields[index]
      );

      const rejection = createDataKeyResolutions.find(
        (result): result is PromiseRejectedResult => result.status === 'rejected'
      );
      if (rejection != null) {
        throw new MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason });
      }
    }

    try {
      const collection = await db.createCollection<TSchema>(name, {
        ...createCollectionOptions,
        encryptedFields,
        timeoutMS: timeoutContext?.csotEnabled()
          ? timeoutContext?.getRemainingTimeMSOrThrow()
          : undefined
      });
      return { collection, encryptedFields };
    } catch (cause) {
      throw new MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause });
    }
  }

  /**

View on GitHub (pinned to dce7939f86)