mongodb/node-mongodb-native · error · MongoCryptCreateDataKeyError

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

Error message

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

What it means

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.

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 3366c21a63)

Solutions

  1. Inspect err.cause for the per-field rejection to identify which field and KMS provider failed.
  2. Verify KMS connectivity and credentials for the configured provider (AWS/GCP/Azure/local).
  3. Ensure the key vault namespace exists and the user has write access; pre-create keys with createDataKey to isolate the failure.

Example fix

// before
try {
  await ce.createEncryptedCollection(db, 'patients', { encryptedFields, provider: 'aws', createCollectionOptions });
} catch (e) { /* opaque */ }

// after
try {
  await ce.createEncryptedCollection(db, 'patients', { encryptedFields, provider: 'aws', createCollectionOptions });
} catch (e) {
  console.error('field failures:', e.cause); // identify which field/KMS failed
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-flight: create one data key to validate KMS + key vault before bulk creation
await ce.createDataKey(provider, { masterKey }).catch(e => { throw new Error('KMS preflight failed: ' + e.message); });

Type guard

// Not applicable: KMS/permissions failure, not a type.

Try / catch

try {
  await ce.createEncryptedCollection(db, name, opts);
} catch (err) {
  if (err.name === 'MongoCryptCreateDataKeyError') {
    console.error('data key failure cause:', err.cause);
    /* fix KMS creds/masterKey, then retry */
  } else throw err;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04). Data as JSON: /data/errors/2420213b26ff26ef.json. Report an issue: GitHub.