0
0
DenoHow-ToBeginner ยท 3 min read

How to Delete Data from Deno KV Store Easily

To delete data from Deno KV, use the delete() method with the key you want to remove. This method is asynchronous and returns true if the key existed and was deleted, or false if the key was not found.
๐Ÿ“

Syntax

The delete() method removes a key-value pair from the Deno KV store.

  • await kv.delete(key): Deletes the entry with the specified key.
  • key: An array representing the key path, e.g., ["user", "123"].
  • The method returns a Promise<boolean> indicating if the key was deleted (true) or not found (false).
typescript
const result = await kv.delete(["your", "key"]);
๐Ÿ’ป

Example

This example shows how to delete a key from Deno KV and check if the deletion was successful.

typescript
import { openKv } from "https://deno.land/x/kv/mod.ts";

const kv = await openKv();

// Set a key-value pair
await kv.set(["session", "token"], "abc123");

// Delete the key
const deleted = await kv.delete(["session", "token"]);

console.log("Deleted:", deleted); // true

// Try deleting again
const deletedAgain = await kv.delete(["session", "token"]);

console.log("Deleted again:", deletedAgain); // false
Output
Deleted: true Deleted again: false
โš ๏ธ

Common Pitfalls

Common mistakes when deleting from Deno KV include:

  • Using a wrong key format (not an array) which causes errors.
  • Assuming delete() throws an error if the key does not exist; it returns false instead.
  • Not awaiting the delete() call, leading to unexpected behavior.
typescript
/* Wrong way: missing await and wrong key type */
// kv.delete("wrongKey"); // โŒ This will cause an error

/* Right way: use await and array key */
await kv.delete(["correct", "key"]); // โœ…
๐Ÿ“Š

Quick Reference

OperationUsageReturns
Delete keyawait kv.delete(["key", "path"])Promise (true if deleted)
Key formatArray of strings or numbersN/A
Error if key missingNo, returns falseN/A
Await requiredYesN/A
โœ…

Key Takeaways

Use await kv.delete(keyArray) to remove a key from Deno KV.
The key must be an array representing the key path.
delete() returns true if the key existed and was deleted, false otherwise.
Always await the delete() call to ensure it completes.
No error is thrown if the key does not exist; check the boolean result instead.