Represents an interface to some Astra database instance. This is the entrypoint for database-level DML, such as creating/deleting collections, connecting to collections, 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.

Db spawning methods let you pass in the default keyspace for the database, which is used for all subsequent db operations in that object, but each method lets you override the keyspace if necessary in its options.

Example

const client = new DataAPIClient('AstraCS:...');

// Connect to a database using a direct endpoint
const db1 = client.db('https://<db_id>-<region>.apps.astra.datastax.com');

// Overrides default options from the DataAPIClient
const db2 = client.db('https://<db_id>-<region>.apps.astra.datastax.com', {
  keyspace: 'my_keyspace',
  useHttp2: false,
});

// Lets you connect using a database ID and region
const db3 = client.db('a6a1d8d6-31bc-4af8-be57-377566f345bf', 'us-east1');

See

  • DataAPIClient.db
  • AstraAdmin.db

Constructors

Properties

#defaultOpts: InternalRootClientOpts
#endpoint?: string
#httpClient: DataAPIHttpClient
_id?: string
_keyspace: KeyspaceRef

Accessors

  • get id(): string
  • The ID of the database, if it's an Astra database. If it's not an Astra database, this will throw an error.

    Returns string

    Throws

    Error - if the database is not an Astra database.

  • get keyspace(): string
  • The default keyspace to use for all operations in this database, unless overridden in a method call.

    Returns string

    Example

    // 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'
    });

Methods

  • 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).

    If using a non-Astra backend, the environment option MUST be set as it is on the DataAPIClient

    Parameters

    • Optional options: AdminSpawnOptions & {
          environment?: "astra";
      }

      Any options to override the default options set when creating the DataAPIClient.

    Returns AstraDbAdmin

    A new AstraDbAdmin instance for this database instance.

    Example

    const admin1 = db.admin();
    const admin2 = db.admin({ adminToken: '<stronger-token>' });

    const keyspaces = await admin1.listKeyspaces();
    console.log(keyspaces);

    Throws

    Error - 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

    Parameters

    • options: AdminSpawnOptions & {
          environment: "dse" | "hcd" | "cassandra" | "other";
      }

      Any options to override the default options set when creating the DataAPIClient.

    Returns DataAPIDbAdmin

    A new AstraDbAdmin instance for this database instance.

    Example

    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);

    Throws

    Error - 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.

    NB. This method does not validate the existence of the collection—it simply creates a reference.

    Unlike the MongoDB driver, this method does not create a collection if it doesn't exist.

    Use Db.createCollection to create a new collection instead.

    Typed as Collection<SomeDoc> by default, but you can specify a schema type to get a typed collection. If left as SomeDoc, the collection will be untyped.

    You can also specify a keyspace in the options parameter, which will override the default keyspace for this database.

    Type Parameters

    Parameters

    Returns Collection<Schema>

    A new, unvalidated, reference to the collection.

    Example

    interface User {
      name: string,
      age?: number,
    }

    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({ nam3: "John" });

    See

    • SomeDoc
    • VectorDoc
  • Establishes references to all the collections in the working/given keyspace.

    You can specify a keyspace in the options parameter, which will override the default keyspace for this Db instance.

    Parameters

    Returns Promise<Collection<SomeDoc>[]>

    A promise that resolves to an array of references to the working Db's collections.

    Example

    // Uses db's default keyspace
    const collections1 = await db.collections();
    console.log(collections1); // [Collection<SomeDoc>, Collection<SomeDoc>]

    // Overrides db's default keyspace
    const collections2 = await db.collections({ keyspace: 'my_keyspace' });
    console.log(collections2); // [Collection<SomeDoc>]

    Deprecated

    • Essentially equivalent to (await db.listCollections()).map(c => new Collection(c.name)); will be removed in an upcoming major release.
  • Send a POST request to the Data API for this database with an arbitrary, caller-provided payload.

    You can specify a collection to target in the options parameter, thereby allowing you to perform arbitrary collection-level operations as well.

    You're also able to specify a keyspace in the options parameter, which will override the default keyspace for this database.

    If no collection is specified, the command will be executed at the database level.

    Parameters

    • command: Record<string, any>

      The command to send to the Data API.

    • Optional options: RunCommandOptions

      Options for this operation.

    Returns Promise<RawDataAPIResponse>

    A promise that resolves to the raw response from the Data API.

    Example

    const colls = await db.command({ findCollections: {} });
    console.log(colls); // { status: { collections: [] } }

    const users = await db.command({ findOne: {} }, { collection: 'users' });
    console.log(users); // { data: { document: null } }
  • Creates a new collection in the database, and establishes a reference to it.

    NB. You are limited in the amount of collections you can create, so be wary when using this command.

    This is a blocking command which performs actual I/O unlike Db.collection, which simply creates an unvalidated reference to a collection.

    If checkExists: false, creation is idempotent, so if the collection already exists with the same options, this method will not throw an error. If the options mismatch, it will throw a DataAPIResponseError.

    Typed as Collection<SomeDoc> by default, but you can specify a schema type to get a typed collection. If left as SomeDoc, the collection will be untyped.

    If vector options are not specified, the collection will not support vector search.

    You can also specify a keyspace in the options parameter, which will override the default keyspace for this database.

    See CreateCollectionOptions for much more information on the options available.

    Type Parameters

    Parameters

    Returns Promise<Collection<Schema>>

    A promised reference to the newly created collection.

    Example

    interface User {
      name: string,
      age?: number,
    }

    const users = await db.createCollection<User>("users");
    users.insertOne({ name: "John" });

    // Untyped collection with custom options in a different keyspace
    const users2 = await db.createCollection("users", {
      keyspace: "my_keyspace",
      defaultId: {
      type: "objectId",
      },
      checkExists: false,
    });

    Throws

    CollectionAlreadyExistsError - if the collection already exists and checkExists is true or unset.

    See

    • SomeDoc
    • VectorDoc
  • 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 default keyspace for this database.

    Parameters

    • name: string

      The name of the collection to drop.

    • Optional options: DropCollectionOptions

      Options for this operation.

    Returns Promise<boolean>

    A promise that resolves to true if the collection was dropped successfully.

    Example

    // Uses db's default keyspace
    const success1 = await db.dropCollection("users");
    console.log(success1); // true

    // Overrides db's default keyspace
    const success2 = await db.dropCollection("users", {
      keyspace: "my_keyspace"
    });
    console.log(success2); // true

    Remarks

    Use with caution. Have steel-toe boots on. Don't say I didn't warn you.

  • Fetches information about the database, such as the database name, region, and other metadata.

    NB. 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.

    Parameters

    Returns Promise<DatabaseInfo>

    A promise that resolves to the database information.

    Example

    const info = await db.info();
    console.log(info.name);

    Throws

    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, using the other overload.

    You can also specify a keyspace in the options parameter, which will override the default keyspace for this database.

    Parameters

    Returns Promise<string[]>

    A promise that resolves to an array of collection names.

    Example

    // [{ name: "users" }, { name: "posts" }]
    console.log(await db.listCollections({ nameOnly: true }));

    See

    CollectionOptions

  • Lists the collections in the database.

    If you want to use only the collection names, set nameOnly to true (or omit it completely), using the other overload.

    You can also specify a keyspace in the options parameter, which will override the default keyspace for this database.

    Parameters

    Returns Promise<FullCollectionInfo[]>

    A promise that resolves to an array of collection info.

    Example

    // [{ name: "users" }, { name: "posts", options: { ... } }]
    console.log(await db.listCollections());

    See

    CollectionOptions

  • 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.

    Parameters

    • keyspace: string

      The keyspace to use

    Returns void

    Example

    // 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' });

    Example

    // If using non-astra, this may be a common idiom:
    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');