Internal
Use DataAPIClient.db to obtain an instance of this class.
Private
Readonly
#defaultPrivate
Readonly
#endpointPrivate
Readonly
#httpPrivate
Optional
Readonly
#idPrivate
Readonly
#keyspacePrivate
Optional
Readonly
#regionThe ID of the database (UUID), if it's an Astra database.
If it's not an Astra database, this will throw an error, as they have no applicable/appropriate ID.
InvalidEnvironmentError - if the database is not an Astra database.
The default keyspace to use for all operations in this database, unless overridden in a method call.
// Uses 'default_keyspace' as the default keyspace for all future db spawns
const client1 = new DataAPIClient('*TOKEN*');
// Overrides the default keyspace for all future db spawns
const client2 = new DataAPIClient('*TOKEN*', {
dbOptions: { keyspace: 'my_keyspace' },
});
// Created with 'default_keyspace' as the default keyspace
const db1 = client1.db('*ENDPOINT*');
// Created with 'my_keyspace' as the default keyspace
const db2 = client1.db('*ENDPOINT*', {
keyspace: 'my_keyspace'
});
// Uses 'default_keyspace'
const coll1 = db1.collection('users');
// Uses 'my_keyspace'
const coll2 = db1.collection('users', {
keyspace: 'my_keyspace'
});
The region of the database (e.g. 'us-east-1'
), if it's an Astra database.
If it's not an Astra database, this will throw an error, as they have no applicable/appropriate region.
InvalidEnvironmentError - if the database is not an Astra database.
Spawns a new AstraDbAdmin instance for this database, used for performing administrative operations on the database, such as managing keyspaces, or getting database information.
The given options will override any default options set when creating the DataAPIClient through a deep merge (i.e. unset properties in the options object will just default to the default options).
Optional
options: AdminOptions & { Any options to override the default options set when creating the DataAPIClient.
A new AstraDbAdmin instance for this database instance.
const admin1 = db.admin();
const admin2 = db.admin({ adminToken: '<stronger-token>' });
const keyspaces = await admin1.listKeyspaces();
console.log(keyspaces);
If using a non-Astra backend, the environment
option MUST be set as it is on the DataAPIClient
If on Astra, this method will return a new AstraDbAdmin instance, which provides a few extra methods for Astra databases, such as AstraDbAdmin.info or AstraDbAdmin.drop.
InvalidEnvironmentError - if the database is not an Astra database.
Spawns a new DataAPIDbAdmin instance for this database, used for performing administrative operations on the database, such as managing keyspaces, or getting database information.
The given options will override any default options set when creating the DataAPIClient through a deep merge (i.e. unset properties in the options object will just default to the default options).
If using a non-Astra backend, the environment
option MUST be set as it is on the DataAPIClient
Any options to override the default options set when creating the DataAPIClient.
A new AstraDbAdmin instance for this database instance.
const client = new DataAPIClient({ environment: 'dse' });
const db = client.db('*ENDPOINT*', { token });
// OK
const admin1 = db.admin({ environment: 'dse' });
// Will throw "mismatching environments" error
const admin2 = db.admin();
const keyspaces = await admin1.listKeyspaces();
console.log(keyspaces);
If using a non-Astra backend, the environment
option MUST be set as it is on the DataAPIClient
If on non-Astra, this method will return a new DataAPIDbAdmin instance, which conforms strictly to the DbAdmin interface, with the DataAPIDbAdmin.createKeyspace method being the only method that differs slightly from the interface version.
InvalidEnvironmentError - if the database is not an Astra database.
Establishes a reference to a collection in the database. This method does not perform any I/O.
NOTE: This method does not validate the existence of the collection—it simply creates a reference.
The name of the collection.
Optional
options: CollectionOptionsOptions for spawning the collection.
A new, unvalidated, reference to the collection.
interface User {
name: string,
age?: number,
}
// Basic usage
const users1 = db.collection<User>('users');
users1.insertOne({ name: 'John' });
// Untyped collection from different keyspace
const users2 = db.collection('users', {
keyspace: 'my_keyspace',
});
users2.insertOne({ 'anything[you]$want': 'John' }); // Dangerous
Unlike the MongoDB Node.js driver, this method does not create a collection if it doesn't exist.
Use Db.createCollection to create a new collection instead.
Collections are inherently untyped, but you can provide your own client-side compile-time schema for type inference and early-bug-catching purposes.
A Collection
is typed as Collection<Schema extends SomeDoc = SomeDoc>
, where:
Schema
is the user-intended type of the documents in the collection.SomeDoc
is set to Record<string, any>
, representing any valid JSON object.Certain datatypes may be represented as TypeScript classes (some native, some provided by astra-db-ts
), however.
You may also provide your own datatypes by providing some custom serialization logic as well (see later section).
Please see Collection for much more info on typing them, and more.
import { UUID, DataAPIVector, ... } from 'astra-db-ts';
interface User {
_id: string,
dob: Date,
friends?: Record<string, UUID>, // UUID is also `astra-db-ts` provided
vector: DataAPIVector,
}
const collection = db.collection<User>('users');
// res.insertedId is of type string
const res = await collection.insertOne({
_id: '123',
dob: new Date(),
friends: { 'Alice': UUID.random() },
vector: new DataAPIVector([1, 2, 3]), // This can also be passed as a number[]
});
Collections are inherently untyped
It is on the user to ensure that the TS type of the Collection
corresponds with the actual CQL table schema, in its TS-deserialized form. Incorrect or dynamic tying could lead to surprising behaviours and easily-preventable errors.
There is no runtime type validation or enforcement of the schema.
Send a POST request to the Data API for this database with an arbitrary, caller-provided payload.
You can specify a table/collection to target in the options parameter, thereby allowing you to perform arbitrary table/collection-level operations as well.
If the keyspace is set to null
, the command will be run at the database level.
If no collection is specified, the command will be executed at the keyspace level.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
The command to send to the Data API.
Optional
options: RunCommandOptionsOptions for this operation.
A promise that resolves to the raw response from the Data API.
const colls = await db.command({ findCollections: {} });
console.log(colls); // { status: { collections: [] } }
const user = await db.command({ findOne: {} }, { collection: 'users' });
console.log(user); // { data: { document: null } }
const post = await db.command({ findOne: {} }, { table: 'posts' });
console.log(post); // { data: { document: null } }
Creates a new collection in the database, and establishes a reference to it.
This is a blocking command which performs actual I/O (unlike Db.collection, which simply creates an unvalidated reference to a collection).
The name of the collection to create.
Optional
options: CreateCollectionOptions<WSchema>Options for the collection.
A promised reference to the newly created collection.
// Most basic usage
const users = await db.createCollection('users');
// With custom options in a different keyspace
const users2 = await db.createCollection('users', {
keyspace: 'my_keyspace',
defaultId: {
type: 'objectId',
},
});
Creating a collection is idempotent as long as the options remain the same; if the collection already exists with the same options, a DataAPIResponseError will be thrown.
("options" mean the createCollection
options actually sent to the server, not things like timeout
which are just client-side).
If vector options are not specified, the collection will not support vector search.
You can enable it by providing a vector
option with the desired configuration, optionally with a vector.service
block to enable vectorize (auto-embedding-generation).
const users = await db.createCollection('users', {
vector: {
service: {
provider: 'nvidia',
modelName: 'NV-Embed-QA',
},
},
});
// Now, `users` supports vector search
await users.insertOne({ $vectorize: 'I like cars!!!' });
await users.fineOne({}, { sort: { $vectorize: 'I like cars!!!' } });
Collections are inherently untyped, but you can provide your own client-side compile-time schema for type inference and early-bug-catching purposes.
A Collection
is typed as Collection<Schema extends SomeDoc = SomeDoc>
, where:
Schema
is the user-intended type of the documents in the collection.SomeDoc
is set to Record<string, any>
, representing any valid JSON object.Certain datatypes may be represented as TypeScript classes (some native, some provided by astra-db-ts
), however.
You may also provide your own datatypes by providing some custom serialization logic as well (see later section).
Please see Collection for much more info on typing them, and more.
import { UUID, DataAPIVector, ... } from 'astra-db-ts';
interface User {
_id: string,
dob: Date,
friends?: Record<string, UUID>, // UUID is also `astra-db-ts` provided
vector: DataAPIVector,
}
const collection = await db.createCollection<User>('users');
// res.insertedId is of type string
const res = await collection.insertOne({
_id: '123',
dob: new Date(),
friends: { 'Alice': UUID.random() },
vector: new DataAPIVector([1, 2, 3]), // This can also be passed as a number[]
});
Collections are inherently untyped
It is on the user to ensure that the TS type of the Collection
corresponds with the actual CQL table schema, in its TS-deserialized form. Incorrect or dynamic tying could lead to surprising behaviours and easily-preventable errors.
There is no runtime type validation or enforcement of the schema.
CollectionAlreadyExistsError - if the collection already exists and checkExists
is true
or unset.
Creates a new table in the database, and establishes a reference to it.
This is a blocking command which performs actual I/O (unlike Db.table, which simply creates an unvalidated reference to a table).
This overload of createTable
infers the TS-equivalent schema of the table from the provided CreateTableDefinition
.
Provide an explicit Schema
type to disable this (e.g. db.createTable<SomeRow>(...)
).
The name of the table to create.
Options for the table.
A promised reference to the newly created table.
// Function to create the actual table
const mkUserTable = () => db.createTable('users', {
definition: {
columns: {
name: 'text',
dob: {
type: 'timestamp',
},
friends: {
type: 'set',
valueType: 'text',
},
},
primaryKey: {
partitionBy: ['name', 'height'],
partitionSort: { dob: 1 },
},
},
});
// Type inference is as simple as that
type User = InferTableSchema<typeof mkUserTable>;
// And now `User` can be used wherever.
const main = async () => {
const table = await mkUserTable();
const found: User | null = await table.findOne({});
};
Creating a table is idempotent if the ifNotExists
option is set to true
. Otherwise, an error will be thrown if a table with the same name is thrown.
If a table is "recreated" with the same name & ifNotExists
is set to true
, but the columns definition differ, the operation will silently succeed, but the original table schema will be retained.
A Table
is typed as Table<Schema extends SomeRow = SomeRow>
, where:
Schema
is the type of the rows in the table (the table schema).SomeRow
is set to Record<string, any>
, representing any valid JSON object.Certain datatypes may be represented as TypeScript classes (some native, some provided by astra-db-ts
), however.
You may also provide your own datatypes by providing some custom serialization logic as well (see later section).
Please see Table for much more info on typing them, and more.
It is on the user to ensure that the TS type of the Table
corresponds with the actual CQL table schema, in its TS-deserialized form. Incorrect or dynamic tying could lead to surprising behaviours and easily-preventable errors.
See Db.createTable, Db.table, and InferTableSchema for much more information about typing.
Creates a new table in the database, and establishes a reference to it.
This is a blocking command which performs actual I/O (unlike Db.table, which simply creates an unvalidated reference to a table).
This overload of createTable
uses the provided Schema
type to type the Table.
Don't provide a Schema
type if you want to infer it from the CreateTableDefinition
via InferTableSchema.
The name of the table to create.
Options for the table.
A promised reference to the newly created table.
interface User {
name: string,
dob: DataAPIDate,
friends?: Set<string>,
}
type UserPK = Pick<User, 'name' | 'dob'>;
const table = await db.createTable<User, UserPK>('users', {
definition: {
columns: {
name: 'text',
dob: {
type: 'timestamp',
},
friends: {
type: 'set',
valueType: 'text',
},
},
primaryKey: {
partitionBy: ['name'],
partitionSort: { dob: 1 },
},
},
});
const found: User | null = await table.findOne({});
Creating a table is idempotent if the ifNotExists
option is set to true
. Otherwise, an error will be thrown if a table with the same name is thrown.
If a table is "recreated" with the same name & ifNotExists
is set to true
, but the columns definition differ, the operation will silently succeed, but the original table schema will be retained.
A Table
is typed as Table<Schema extends SomeRow = SomeRow>
, where:
Schema
is the type of the rows in the table (the table schema).SomeRow
is set to Record<string, any>
, representing any valid JSON object.Certain datatypes may be represented as TypeScript classes (some native, some provided by astra-db-ts
), however.
You may also provide your own datatypes by providing some custom serialization logic as well (see later section).
Please see Table for much more info on typing them, and more.
It is on the user to ensure that the TS type of the Table
corresponds with the actual CQL table schema, in its TS-deserialized form. Incorrect or dynamic tying could lead to surprising behaviours and easily-preventable errors.
See Db.createTable, Db.table, and InferTableSchema for much more information about typing.
Drops a collection from the database, including all the contained documents.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
The name of the collection to drop.
Optional
options: DropCollectionOptionsOptions for this operation.
A promise that resolves to true
if the collection was dropped successfully.
// Uses db's working keyspace
const success1 = await db.dropCollection('users');
console.log(success1); // true
// Overrides db's working keyspace
const success2 = await db.dropCollection('users', {
keyspace: 'my_keyspace'
});
console.log(success2); // true
Use with caution. Have steel-toe boots on. Don't say I didn't warn you.
Drops a table from the database, including all the contained rows.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
The name of the table to drop.
Optional
options: DropTableOptionsOptions for this operation.
A promise that resolves to true
if the table was dropped successfully.
// Uses db's working keyspace
const success1 = await db.dropTable('users');
console.log(success1); // true
// Overrides db's working keyspace
const success2 = await db.dropTable('users', {
keyspace: 'my_keyspace'
});
console.log(success2); // true
Use with caution. Wear a mask. Don't say I didn't warn you.
Drops an index from the database.
This operation is idempotent if ifExists
is set to true
.
See Table.createIndex & Table.createVectorIndex
The name of the index is must actually be unique per keyspace, which is why this is a database-level command: to make it clear that the index is being dropped from the keyspace, not a specific table.
The name of the index to drop.
Optional
options: TableDropIndexOptionsThe options for this operation.
A promise that resolves when the index is dropped.
Fetches information about the database, such as the database name, region, and other metadata.
NOTE: Only available for Astra databases.
For the full, complete, information, see AstraDbAdmin.info.
The method issues a request to the DevOps API each time it is invoked, without caching mechanisms; this ensures up-to-date information for usages such as real-time collection validation by the application.
Optional
options: WithTimeout<"databaseAdminTimeoutMs">A promise that resolves to the database information.
const info = await db.info();
console.log(info.name);
This operation requires a call to the DevOps API, which is only available on Astra databases. As such, this method will throw an error if the database is not an Astra database.
Error - if the database is not an Astra database.
Lists the collection names in the database.
If you want to include the collection options in the response, set nameOnly
to false
(or omit it completely),
using the other overload.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
Options for this operation.
A promise that resolves to an array of collection names.
// ['users', 'posts']
console.log(await db.listCollections({ nameOnly: true }));
Lists the collections in the database.
If you want to use only the collection names, set nameOnly
to true
, using the other overload.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
Optional
options: ListCollectionsOptions & { Options for this operation.
A promise that resolves to an array of collection info.
// [{ name: 'users' }, { name: 'posts', options: { ... } }]
console.log(await db.listCollections());
Lists the table names in the database.
If you want to include the table options in the response, set nameOnly
to false
(or omit it completely),
using the other overload.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
Options for this operation.
A promise that resolves to an array of table names.
// ['users', 'posts']
console.log(await db.listTables({ nameOnly: true }));
Lists the tables in the database.
If you want to use only the table names, set nameOnly
to true
, using the other overload.
You can also specify a keyspace in the options parameter, which will override the working keyspace for this Db
instance.
Optional
options: ListTablesOptions & { Options for this operation.
A promise that resolves to an array of table info.
// [{ name: 'users' }, { name: 'posts', definition: { ... } }]
console.log(await db.listTables());
Establishes a reference to a table in the database. This method does not perform any I/O.
NOTE: This method does not validate the existence of the table—it simply creates a reference.
The name of the table.
Optional
options: TableOptionsOptions for spawning the table.
A new, unvalidated, reference to the table.
interface User {
name: string,
age?: number,
}
// Basic usage
const users1 = db.table<User>('users');
users1.insertOne({ name: 'John' });
// Untyped table from different keyspace
const users2 = db.table('users', {
keyspace: 'my_keyspace',
});
users2.insertOne({ 'anything[you]$want': 'John' }); // Dangerous
This method does not create a table if it doesn't exist.
Use Db.createTable to create a new table instead.
A Table
is typed as Table<Schema extends SomeRow = SomeRow>
, where:
Schema
is the type of the rows in the table (the table schema).SomeRow
is set to Record<string, any>
, representing any valid JSON object.Certain datatypes may be represented as TypeScript classes (some native, some provided by astra-db-ts
), however.
You may also provide your own datatypes by providing some custom serialization logic as well (see later section).
Please see Table for much more info on typing them, and more.
import { DataAPIDate, UUID, DataAPIVector, ... } from 'astra-db-ts';
interface User {
id: string, // Partition key
dob: DataAPIDate, // Clustering (partition sort) key
friends: Map<string, UUID>,
vector: DataAPIVector,
}
type UserPK = Pick<User, 'id' | 'dob'>;
const table = db.table<User, UserPK>('users');
// res.insertedId is of type { id: string }
const res = await table.insertOne({
id: '123',
dob: new DataAPIDate(new Date()),
friends: new Map([['Alice', UUID.random()]]),
vector: new DataAPIVector([1, 2, 3]), // Class enables encoding optimization
});
It is on the user to ensure that the TS type of the Table
corresponds with the actual CQL table schema, in its TS-deserialized form. Incorrect or dynamic tying could lead to surprising behaviours and easily-preventable errors.
See Db.createTable, Db.table, and InferTableSchema for much more information about typing.
Sets the default working keyspace of the Db
instance. Does not retroactively update any previous collections
spawned from this Db
to use the new keyspace.
See Db for more info on "working keyspaces".
The keyspace to use
// Spawns a `Db` with default working keyspace `my_keyspace`
const db = client.db('<endpoint>', { keyspace: 'my_keyspace' });
// Gets a collection from keyspace `my_keyspace`
const coll1 = db.collection('my_coll');
// `db` now uses `my_other_keyspace` as the default keyspace for all operations
db.useKeyspace('my_other_keyspace');
// Gets a collection from keyspace `my_other_keyspace`
// `coll1` still uses keyspace `my_keyspace`
const coll2 = db.collection('my_other_coll');
// Gets `my_coll` from keyspace `my_keyspace` again
// (The default keyspace is still `my_other_keyspace`)
const coll3 = db.collection('my_coll', { keyspace: 'my_keyspace' });
updateDbKeyspace
in DbAdmin.createKeyspace
If you want to create a Db
in a not-yet-existing keyspace, you can use the updateDbKeyspace
option in DbAdmin.createKeyspace to set the default keyspace of the Db
instance to the new keyspace.
This may be a common idiom when working with non-Astra databases.
const client = new DataAPIClient({ environment: 'dse' });
const db = client.db('<endpoint>', { token: '<token>' });
// Will internally call `db.useKeyspace('new_keyspace')`
await db.admin().createKeyspace('new_keyspace', {
updateDbKeyspace: true,
});
// Creates collection in keyspace `new_keyspace` by default now
const coll = db.createCollection('my_coll');
Overview
Represents an interface to some Data-API-enabled database instance. This is the entrypoint for database-level DML, such as creating/deleting collections/tables, connecting to collections/tables, and executing arbitrary commands.
Shouldn't be instantiated directly; use DataAPIClient.db to obtain an instance of this class.
Note that creating an instance of a
Db
doesn't trigger actual database creation; the database must have already existed beforehand. If you need to create a new database, use the AstraAdmin class.Example
The "working keyspace"
The
Db
class has a concept of a "working keyspace", which is the default keyspace used for all operations in the database. This can be overridden in each method call, but if not, the default keyspace is used.If no explicit keyspace is provided when creating the
Db
instance, it will default to:default_keyspace
db.useKeyspace()
mutator methodupdateDbKeyspace
parameter indbAdmin.createKeyspace()
Changing the working namespaces does NOT retroactively update any collections/tables spawned from this
Db
instance.See Db.useKeyspace and DbAdmin.createKeyspace for more information.
Example
Astra vs. non-Astra
The
Db
class is designed to work with both Astra and non-Astra databases. However, there are some differences in behaviour between the two:db.id
anddb.region
respectivelydb.info()
method, which provides detailed information about the databasedb.admin()
method will return differently depending on the environmentenvironment
option must also be set in theadmin()
method)See