Get a collection (TypeScript)
Gets a reference to a collection for use with the Data API clients.
|
Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart. |
Result
Returns a Collection<Schema> object that corresponds to the specified collection name.
This method returns a Collection object even for collections that don’t exist.
A Collection is typed as Collection<Schema>, where Schema defaults to SomeDoc (Record<string, any>).
Providing the specific Schema type enables stronger typing for collection operations.
For more information, see Typing Collections and Tables.
Parameters
Use the collection method, which belongs to the Db class.
Method signature
collection <Schema extends SomeDoc = SomeDoc>(
name: string,
options?: {
keyspace?: string,
logging?: DataAPILoggingConfig,
serdes?: CollectionSerDesConfig,
timeoutDefaults?: TimeoutDescriptor,
}
): Collection<Schema>
| Name | Type | Summary |
|---|---|---|
|
|
The name of the collection. |
|
Optional.
The options for this operation.
See Properties of |
| Name | Type | Summary |
|---|---|---|
|
Optional if you specified a working keyspace when you created the Default: The working keyspace set when you created the |
|
|
Optional. The configuration for logging events emitted by the DataAPIClient. |
|
|
Optional. The configuration for serialization/deserialization by the DataAPIClient. For more information, see Custom Ser/Des. |
|
|
Optional. The default timeout(s) to apply to operations performed on this Collection instance.
You can specify For more information about the |
Examples
The following examples demonstrate how to get a collection.
Get a collection
-
Typed collections
-
Untyped collections
You can manually define a client-side type for your collection to help statically catch errors.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
// Define the type for the collection
interface User {
name: string;
age?: number;
}
// Get a collection
(async function () {
const collection = await database.collection<User>("COLLECTION_NAME");
})();
If you don’t pass a type parameter, the collection remains untyped. This is a more flexible but less type-safe option.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";
// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace: "KEYSPACE_NAME",
});
// Get a collection
(async function () {
const collection = await database.collection("COLLECTION_NAME");
})();
Client reference
For more information, see the client reference.