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 namespace for the database, which is used for all subsequent db operations in that object, but each method lets you override the namespace 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', {
  namespace: 'my_namespace',
  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
#httpClient: DataAPIHttpClient
_id?: string
_namespace: NamespaceRef

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 namespace(): string
  • The default namespace to use for all operations in this database, unless overridden in a method call.

    Returns string

    Example

    // Uses 'default_keyspace' as the default namespace for all future db spawns
    const client1 = new DataAPIClient('*TOKEN*');

    // Overrides the default namespace for all future db spawns
    const client2 = new DataAPIClient('*TOKEN*', {
      dbOptions: { namespace: 'my_namespace' },
    });

    // Created with 'default_keyspace' as the default namespace
    const db1 = client1.db('*ENDPOINT*');

    // Created with 'my_namespace' as the default namespace
    const db2 = client1.db('*ENDPOINT*', {
      namespace: 'my_namespace'
    });

    // Uses 'default_keyspace'
    const coll1 = db1.collection('users');

    // Uses 'my_namespace'
    const coll2 = db1.collection('users', {
      namespace: 'my_namespace'
    });

Methods

  • Spawns a new AstraDbAdmin instance for this database, used for performing administrative operations on the database, such as managing namespaces, 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 namespaces = await admin1.listNamespaces();
    console.log(namespaces);

    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 namespaces, 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 namespaces = await admin1.listNamespaces();
    console.log(namespaces);

    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 namespace in the options parameter, which will override the default namespace 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 namespace
    const users2 = db.collection("users", {
      namespace: "my_namespace"
    });
    users2.insertOne({ nam3: "John" });

    See

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

    You can specify a namespace in the options parameter, which will override the default namespace 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 namespace
    const collections1 = await db.collections();
    console.log(collections1); // [Collection<SomeDoc>, Collection<SomeDoc>]

    // Overrides db's default namespace
    const collections2 = await db.collections({ namespace: 'my_namespace' });
    console.log(collections2); // [Collection<SomeDoc>]
  • 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 namespace in the options parameter, which will override the default namespace 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 namespace in the options parameter, which will override the default namespace 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 namespace
    const users2 = await db.createCollection("users", {
      namespace: "my_namespace",
      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 namespace in the options parameter, which will override the default namespace 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 namespace
    const success1 = await db.dropCollection("users");
    console.log(success1); // true

    // Overrides db's default namespace
    const success2 = await db.dropCollection("users", {
      namespace: "my_namespace"
    });
    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 namespace in the options parameter, which will override the default namespace 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 namespace in the options parameter, which will override the default namespace 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 namespace of the Db instance. Does not retroactively update any previous collections spawned from this Db to use the new namespace.

    Parameters

    • namespace: string

      The namespace to use

    Returns void

    Example

    // Spawns a `Db` with default working namespace `my_namespace`
    const db = client.db('<endpoint>', { namespace: 'my_namespace' });

    // Gets a collection from namespace `my_namespace`
    const coll1 = db.collection('my_coll');

    // `db` now uses `my_other_namespace` as the default namespace for all operations
    db.useNamespace('my_other_namespace');

    // Gets a collection from namespace `my_other_namespace`
    // `coll1` still uses namespace `my_namespace`
    const coll2 = db.collection('my_other_coll');

    // Gets `my_coll` from namespace `my_namespace` again
    // (The default namespace is still `my_other_namespace`)
    const coll3 = db.collection('my_coll', { namespace: 'my_namespace' });

    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.useNamespace('new_namespace')`
    await db.admin().createNamespace('new_namespace', {
      updateDbNamespace: true,
    });

    // Creates collection in namespace `new_namespace` by default now
    const coll = db.createCollection('my_coll');