Skip to main content
Module

x/kvdex/mod.ts>Collection

Database wrapper for Deno KV
Go to Latest
class Collection
Re-export
import { Collection } from "https://deno.land/x/kvdex@v0.11.0/mod.ts";

Represents a collection of documents stored in the KV store.

Contains methods for working on documents in the collection.

Constructors

new
Collection(
kv: Deno.Kv,
key: KvKey,
options?: T2,
)

Create a new collection for handling documents in the KV store.

Example:

const kv = await Deno.openKv()
const numbers = new Collection<number>(kv, ["numbers"])

Properties

protected
kv: Deno.Kv
readonly
_idGenerator: IdGenerator<KvValue>
readonly
_keys: CollectionKeys

Methods

protected
handleMany(fn: (doc: Document<T1>) => unknown, options?: ListOptions<T1>)

Perform operations on lists of documents in the collection.

protected
updateDocument(doc: Document<T1>, data: UpdateData<T1>)

Update a document with new data.

add(data: T1)

Adds a new document to the KV store with a randomely generated id.

Example:

const result = await db.users.add({
  username: "oli",
  age: 24
})
addMany(...entries: T1[])

Adds multiple documents to the KV store.

Example:

// Adds 5 new document entries to the KV store.
await results = await db.numbers.addMany(1, 2, 3, 4, 5)

// Only adds the first entry, as "username" is defined as a primary index and cannot have duplicates
await results = await db.users.addMany(
  {
    username: "oli",
    age: 24
  },
  {
    username: "oli",
    age: 56
  }
)
count(options?: CountOptions<T1>)

Counts the number of documents in the collection.

Example:

// Returns the total number of user documents in the KV store
const count = await db.users.count()

// Returns the number of users with age > 20
const count = await db.users.count({
  filter: doc => doc.value.age > 20
})
delete(...ids: KvId[])

Deletes one or more documents with the given ids from the KV store.

Example:

await db.users.delete("oliver")

await db.users.delete("user1", "user2", "user3")

Deletes multiple documents from the KV store according to the given options.

If no options are given, all documents are deleted.

Example:

// Delete all
await db.users.deleteMany()

// Delete only users with username = "oli"
await db.users.deleteMany({
  filter: doc => doc.value.username === "oli"
})
enqueue(data: unknown, options?: EnqueueOptions)

Add data to the collection queue to be delivered to the queue listener via db.collection.listenQueue(). The data will only be received by queue listeners on the specified collection. The method takes an optional options argument that can be used to set a delivery delay.

Example:

// Immediate delivery
await db.users.enqueue("some data")

// Delay of 2 seconds before delivery
await db.users.enqueue("some data", {
  delay: 2_000
})
find(id: KvId, options?: FindOptions)

Finds a document with the given id in the KV store.

Example:

const userDoc1 = await db.users.find("user1")

const userDoc2 = await db.users.find("user2", {
  consistency: "eventual" // "strong" by default
})
findMany(ids: KvId[], options?: FindManyOptions)

Finds multiple documents with the given array of ids in the KV store.

Example:

const userDocs1 = await db.users.findMany(["user1", "user2", "user3"])

const userDocs2 = await db.users.findMany(["user1", "user2", "user3"], {
  consistency: "eventual" // "strong" by default
})
forEach(fn: (doc: Document<T1>) => void, options?: ListOptions<T1>)

Executes a callback function for every document according to the given options.

If no options are given, the callback function is executed for all documents in the collection.

Example:

// Print all usernames
await db.users.forEach(doc => console.log(doc.value.username))

// Print all usernames of users with age < 18
await db.users.forEach(doc => console.log(doc.value.username), {
  filter: doc => doc.value.age < 18
})
getMany(options?: ListOptions<T1>)

Retrieves multiple documents from the KV store according to the given options.

If no options are given, all documents are retrieved.

Example:

// Get all users
const { result } = await db.users.getMany()

// Only get users with username that starts with "a"
const { result } = await db.users.getMany({
  filter: doc => doc.value.username.startsWith("a")
})

Listen for data from the collection queue that was enqueued with db.collection.enqueue(). Will only receive data that was enqueued to the specific collection queue. Takes a handler function as argument.

Example:

// Prints the data to console when recevied
db.users.listenQueue((data) => console.log(data))

// Sends post request when data is received
db.users.listenQueue(async (data) => {
  const dataBody = JSON.stringify(data)

  const res = await fetch("...", {
    method: "POST",
    body: dataBody
  })

  console.log("POSTED:", dataBody, res.ok)
})
map<TMapped>(fn: (doc: Document<T1>) => TMapped, options?: ListOptions<T1>)

Executes a callback function for every document according to the given options.

If no options are given, the callback function is executed for all documents in the collection.

The results from the callback function are returned as a list.

Example

// Maps from all user documents to a list of all user document ids
const { result } = await db.users.map(doc => doc.id)

// Maps from users with age > 20 to a list of usernames
const { result } = await db.users.map(doc => doc.value.username, {
  filter: doc => doc.value.age > 20
})
set(id: KvId, data: T1)

Adds a new document with the given id to the KV store.

Example:

const result = await db.users.add("oliver", {
  username: "oli",
  age: 24
})
update(id: KvId, data: UpdateData<T1>): Promise<CommitResult<T1>>

Updates a document with the given id in the KV store.

For primitive values, arrays and built-in objects, this method overrides the old value with the new one.

For custom object types, this method merges the new data with the exisiting data.

Example:

const result1 = await db.numbers.update("num1", 10)

const result2 = await db.users.update("oliver", {
  age: 30 // Partial update, only updates the age field
})
updateMany(data: UpdateData<T1>, options?: ListOptions<T1>)

Update the value of multiple existing documents in the collection.

Example:

// Updates all user documents and sets name = 67
await db.users.updateMany({ age: 67 })

// Updates all user documents where the user's age is above 20
await db.users.updateMany({ age: 67 }, {
  filter: (doc) => doc.value.age > 20,
})

// Only updates first user document, as username is a primary index
const { result } = await db.users.updateMany({ username: "XuserX" })

const success = result.every(commitResult => commitResult.ok)
console.log(success) // false