Collection Management
Check if a Collection Exists
The exist
method checks whether a given collection exists in the specified database.
Definition
await zkdb.db(databaseName: string)
.collection(collectionName: string)
.exist(): Promise<boolean>;
Parameters
- None
Returns
Promise<boolean>
: Returnstrue
if the collection exists in the database,false
if it doesn't exist. This is useful for conditional collection creation, validation checks, and preventing errors when attempting operations on non-existent collections.
Example
import { ZkDatabase } from 'zkdb';
const zkdb = await ZkDatabase.connect({
userName: "chiro-user",
privateKey: "EKFTciRxyxshZjimay9sktsn7v5PvmC5zPq7q4JnitHUytxUVnFP",
environment: "node",
// This URL is for test environment
url: "https://api.zkdatabase.org/graphql",
});
await zkdb.auth.signIn();
const dbTest = zkdb.db('zkdb_test');
await dbTest.collection('Shirt').exist();
await zkdb.auth.signOut();
List Collections
The zkDatabase library provides the collectionList
method to retrieve a list of all collections within a specified database. This function is particularly useful for administrators and developers looking to understand the database structure, inspect available collections, or perform batch operations across multiple collections.
Definition
The collectionList
function is called on a database object, and it returns a promise that resolves to an array of collections.
await zkdb.db(databaseName: string).collectionList(): Promise<string[]>;
Parameters
- None
Returns
Promise<string[]>
: ThecollectionList
method returns aPromise
that resolves to an array ofstring
. Each string represents the name of a collection within the specified database. This list provides insights into the database's structure and can help in planning further operations or analyses.
Example
import { ZkDatabase } from 'zkdb';
const zkdb = await ZkDatabase.connect({
userName: "chiro-user",
privateKey: "EKFTciRxyxshZjimay9sktsn7v5PvmC5zPq7q4JnitHUytxUVnFP",
environment: "node",
// This URL is for test environment
url: "https://api.zkdatabase.org/graphql",
});
await zkdb.auth.signIn();
const dbTest = zkdb.db('zkdb_test');
console.log('Collections in zkdb_test:', await dbTest.collectionList());
await zkdb.auth.signOut();
Result:
The result of the collectionList
method will be an array containing the names of collections or detailed information about each collection, depending on the implementation specifics. For example:
Collections in zkdb_test: [
'users',
'products',
'orders',
// ...other collection names
]
This document provides a clear and structured explanation for retrieving collections using zkDatabase, ensuring users understand the method's functionality, parameters, and expected outcomes.