An object representing a single ArangoDB database. All arangojs collections, cursors, analyzers and so on are linked to a Database object.

Constructors

Accessors

Methods

acquireHostList analyzer analyzers availability beginTransaction clearQueryCache clearSlowQueries clearUserAccessLevel close collection collections commitLocalServiceState compact computeClusterRebalance createAnalyzer createCollection createDatabase createEdgeCollection createGraph createHotBackup createJob createUser createUserFunction createView database databases deleteAllJobResults deleteExpiredJobResults deleteHotBackup downloadService dropDatabase dropUserFunction engine engineStats executeClusterRebalance executeTransaction exists explain get getClusterImbalance getHotBackups getLicense getLogEntries getLogLevel getQueryCacheProperties getService getServiceConfiguration getServiceDependencies getServiceDocumentation getServiceReadme getServiceScripts getUser getUserAccessLevel getUserDatabases graph graphs installService job killQuery listAnalyzers listCollections listCompletedJobs listDatabases listGraphs listLogMessages listPendingJobs listQueryCacheEntries listRunningQueries listServices listSlowQueries listTransactions listUserDatabases listUserFunctions listUsers listViews login parse query queryRules queryTracking rebalanceCluster removeUser renameCollection renameView renewAuthToken replaceService replaceServiceConfiguration replaceServiceDependencies replaceUser restoreHotBackup route runServiceScript runServiceTests setLicense setLogLevel setQueryCacheProperties setResponseQueueTimeSamples setServiceDevelopmentMode setUserAccessLevel shutdown status supportInfo time transaction transactions uninstallService updateServiceConfiguration updateServiceDependencies updateUser upgradeService useBasicAuth useBearerAuth userDatabases version view views waitForPropagation withTransaction

Constructors

  • Creates a new Database instance with its own connection pool.

    See also Database#database.

    Parameters

    • Optional config: ConfigOptions

      An object with configuration options.

    Returns Database

    Example

    const db = new Database({
    url: "http://127.0.0.1:8529",
    databaseName: "my_database",
    auth: { username: "admin", password: "hunter2" },
    });
  • Creates a new Database instance with its own connection pool.

    See also Database#database.

    Parameters

    • url: string | string[]

      Base URL of the ArangoDB server or list of server URLs. Equivalent to the url option in configuration.ConfigOptions.

    • Optional name: string

    Returns Database

    Example

    const db = new Database("http://127.0.0.1:8529", "my_database");
    db.useBasicAuth("admin", "hunter2");

Accessors

  • get name(): string
  • Name of the ArangoDB database this instance represents.

    Returns string

Methods

  • Updates the URL list by requesting a list of all coordinators in the cluster and adding any endpoints not initially specified in the configuration.ConfigOptions.

    For long-running processes communicating with an ArangoDB cluster it is recommended to run this method periodically (e.g. once per hour) to make sure new coordinators are picked up correctly and can be used for fail-over or load balancing.

    Parameters

    • overwrite: boolean = false

      If set to true, the existing host list will be replaced instead of extended.

    Returns Promise<void>

    Example

    const db = new Database();
    const interval = setInterval(
    () => db.acquireHostList(),
    5 * 60 * 1000 // every 5 minutes
    );

    // later
    clearInterval(interval);
    system.close();
  • Returns an analyzers.Analyzer instance representing the Analyzer with the given analyzerName.

    Parameters

    • analyzerName: string

    Returns Analyzer

    Example

    const db = new Database();
    const analyzer = db.analyzer("some-analyzer");
    const info = await analyzer.get();
  • Fetches availability information about the server.

    Parameters

    • graceful: boolean = false

      If set to true, the method will always return false instead of throwing an error; otherwise false will only be returned when the server responds with a 503 status code or an ArangoDB error with a code of 503, such as during shutdown.

    Returns Promise<ServerAvailability>

    Example

    const availability = await db.availability();
    // availability is either "default", "readonly", or false
  • Clears the AQL query results cache of the current database.

    Returns Promise<void>

    Example

    const db = new Database();
    await db.clearQueryCache();
    // Cache is now cleared
  • Clears the list of recent slow queries.

    See also Database#listSlowQueries.

    Returns Promise<void>

    Example

    const db = new Database();
    await db.clearSlowQueries();
    // Slow query list is now cleared
  • Clears the given ArangoDB user's access level for the database, or the given collection in the given database.

    Parameters

    • username: string

      Name of the ArangoDB user to clear the access level for.

    • options: UserAccessLevelOptions

      Database and/or collection to clear the access level for.

    Returns Promise<ArangoApiResponse<Record<string, AccessLevel>>>

    Example

    const db = new Database();
    await db.clearUserAccessLevel("steve");
    // The access level of the user "steve" has been cleared for the current
    // database.

    Example

    const db = new Database();
    await db.clearUserAccessLevel("steve", { database: "staging" });
    // The access level of the user "steve" has been cleared for the "staging"
    // database.

    Example

    const db = new Database();
    await db.clearUserAccessLevel("steve", { collection: "pokemons" });
    // The access level of the user "steve" has been cleared for the
    // "pokemons" collection in the current database.

    Example

    const db = new Database();
    await db.clearUserAccessLevel("steve", {
    database: "staging",
    collection: "pokemons"
    });
    // The access level of the user "steve" has been cleared for the
    // "pokemons" collection in the "staging" database.

    Example

    const db = new Database();
    const staging = db.database("staging");
    await db.clearUserAccessLevel("steve", { database: staging });
    // The access level of the user "steve" has been cleared for the "staging"
    // database.

    Example

    const db = new Database();
    const staging = db.database("staging");
    await db.clearUserAccessLevel("steve", {
    collection: staging.collection("pokemons")
    });
    // The access level of the user "steve" has been cleared for the
    // "pokemons" collection in database "staging".
  • Closes all active connections of this database instance.

    Can be used to clean up idling connections during longer periods of inactivity.

    Note: This method currently has no effect in the browser version of arangojs.

    Returns void

    Example

    const db = new Database();
    const sessions = db.collection("sessions");
    // Clean up expired sessions once per hour
    setInterval(async () => {
    await db.query(aql`
    FOR session IN ${sessions}
    FILTER session.expires < DATE_NOW()
    REMOVE session IN ${sessions}
    `);
    // Making sure to close the connections because they're no longer used
    system.close();
    }, 1000 * 60 * 60);
  • Fetches all collections from the database and returns an array of Collection instances.

    In TypeScript these instances implement both the collections.DocumentCollection and collections.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.

    See also Database#listCollections.

    Parameters

    • excludeSystem: boolean = true

      Whether system collections should be excluded.

    Returns Promise<(DocumentCollection<any, any> & EdgeCollection<any, any>)[]>

    Example

    const db = new Database();
    const collections = await db.collections();
    // collections is an array of DocumentCollection and EdgeCollection
    // instances not including system collections

    Example

    const db = new Database();
    const collections = await db.collections(false);
    // collections is an array of DocumentCollection and EdgeCollection
    // instances including system collections
  • Writes all locally available services to the database and updates any service bundles missing in the database.

    Parameters

    • replace: boolean = false

      If set to true, outdated services will also be committed. This can be used to solve some consistency problems when service bundles are missing in the database or were deleted manually.

    Returns Promise<void>

    Example

    await db.commitLocalServiceState();
    // all services available on the coordinator have been written to the db

    Example

    await db.commitLocalServiceState(true);
    // all service conflicts have been resolved in favor of this coordinator
  • Compacts all databases on the server.

    Parameters

    Returns Promise<void>

  • Computes a set of move shard operations to rebalance the cluster.

    Parameters

    Returns Promise<ClusterRebalanceResult>

    Example

    const db = new Database();
    const result = await db.computerClusterRebalance({
    moveLeaders: true,
    moveFollowers: true
    });
    if (result.moves.length) {
    await db.executeClusterRebalance(result.moves);
    }
  • Creates a new Analyzer with the given analyzerName and options, then returns an analyzers.Analyzer instance for the new Analyzer.

    Parameters

    • analyzerName: string

      Name of the Analyzer.

    • options: CreateAnalyzerOptions

      An object defining the properties of the Analyzer.

    Returns Promise<Analyzer>

    Example

    const db = new Database();
    const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });
    // the identity Analyzer "potatoes" now exists
  • Creates a new collection with the given collectionName and options, then returns a collections.DocumentCollection instance for the new collection.

    Type Parameters

    • EntryResultType extends Record<string, any> = any

      Type to represent document contents returned by the server (including computed properties).

    • EntryInputType extends Record<string, any> = EntryResultType

      Type to represent document contents passed when inserting or replacing documents (without computed properties).

    Parameters

    • collectionName: string

      Name of the new collection.

    • Optional options: CollectionPropertiesOptions & {
          distributeShardsLike?: string;
          enforceReplicationFactor?: boolean;
          keyOptions?: CollectionKeyOptions;
          numberOfShards?: number;
          shardKeys?: string[];
          shardingStrategy?: ShardingStrategy;
          smartGraphAttribute?: string;
          smartJoinAttribute?: string;
          waitForSyncReplication?: boolean;
      } & {
          type?: DOCUMENT_COLLECTION;
      }

      Options for creating the collection.

    Returns Promise<DocumentCollection<EntryResultType, EntryInputType>>

    Example

    const db = new Database();
    const documents = db.createCollection("persons");

    Example

    interface Person {
    name: string;
    }
    const db = new Database();
    const documents = db.createCollection<Person>("persons");
  • Creates a new edge collection with the given collectionName and options, then returns an collections.EdgeCollection instance for the new edge collection.

    Type Parameters

    • EntryResultType extends Record<string, any> = any

      Type to represent edge document contents returned by the server (including computed properties).

    • EntryInputType extends Record<string, any> = EntryResultType

      Type to represent edge document contents passed when inserting or replacing documents (without computed properties).

    Parameters

    • collectionName: string

      Name of the new collection.

    • options: CollectionPropertiesOptions & {
          distributeShardsLike?: string;
          enforceReplicationFactor?: boolean;
          keyOptions?: CollectionKeyOptions;
          numberOfShards?: number;
          shardKeys?: string[];
          shardingStrategy?: ShardingStrategy;
          smartGraphAttribute?: string;
          smartJoinAttribute?: string;
          waitForSyncReplication?: boolean;
      } & {
          type: EDGE_COLLECTION;
      }

      Options for creating the collection.

    Returns Promise<EdgeCollection<EntryResultType, EntryInputType>>

    Example

    const db = new Database();
    const edges = db.createCollection("friends", {
    type: CollectionType.EDGE_COLLECTION
    });

    Example

    interface Friend {
    startDate: number;
    endDate?: number;
    }
    const db = new Database();
    const edges = db.createCollection<Friend>("friends", {
    type: CollectionType.EDGE_COLLECTION
    });
  • Creates a new database with the given databaseName with the given options and returns a Database instance for that database.

    Parameters

    • databaseName: string

      Name of the database to create.

    • Optional options: CreateDatabaseOptions

      Options for creating the database.

    Returns Promise<Database>

    Example

    const db = new Database();
    const info = await db.createDatabase("mydb", {
    users: [{ username: "root" }]
    });
    // the database has been created
  • Creates a new database with the given databaseName with the given users and returns a Database instance for that database.

    Parameters

    • databaseName: string

      Name of the database to create.

    • users: CreateDatabaseUserOptions[]

      Database users to create with the database.

    Returns Promise<Database>

    Example

    const db = new Database();
    const info = await db.createDatabase("mydb", [{ username: "root" }]);
    // the database has been created
  • Creates a new edge collection with the given collectionName and options, then returns an collections.EdgeCollection instance for the new edge collection.

    This is a convenience method for calling Database#createCollection with options.type set to EDGE_COLLECTION.

    Type Parameters

    • EntryResultType extends Record<string, any> = any

      Type to represent edge document contents returned by the server (including computed properties).

    • EntryInputType extends Record<string, any> = EntryResultType

      Type to represent edge document contents passed when inserting or replacing documents (without computed properties).

    Parameters

    • collectionName: string

      Name of the new collection.

    • Optional options: CreateCollectionOptions

      Options for creating the collection.

    Returns Promise<EdgeCollection<EntryResultType, EntryInputType>>

    Example

    const db = new Database();
    const edges = db.createEdgeCollection("friends");

    Example

    interface Friend {
    startDate: number;
    endDate?: number;
    }
    const db = new Database();
    const edges = db.createEdgeCollection<Friend>("friends");
  • Creates a graph with the given graphName and edgeDefinitions, then returns a graphs.Graph instance for the new graph.

    Parameters

    • graphName: string

      Name of the graph to be created.

    • edgeDefinitions: EdgeDefinitionOptions[]

      An array of edge definitions.

    • Optional options: CreateGraphOptions

      An object defining the properties of the graph.

    Returns Promise<Graph>

  • (Enterprise Edition only.) Creates a hot backup of the entire ArangoDB deployment including all databases, collections, etc.

    Returns an object describing the backup result.

    Parameters

    Returns Promise<HotBackupResult>

    Example

    const info = await db.createHotBackup();
    // a hot backup has been created
  • Creates an async job by executing the given callback function. The first database request performed by the callback will be marked for asynchronous execution and its result will be made available as an async job.

    Returns a jobs.Job instance that can be used to retrieve the result of the callback function once the request has been executed.

    Type Parameters

    • T

    Parameters

    • callback: (() => Promise<T>)

      Callback function to execute as an async job.

        • (): Promise<T>
        • Returns Promise<T>

    Returns Promise<Job<T>>

    Example

    const db = new Database();
    const job = await db.createJob(() => db.collections());
    while (!job.isLoaded) {
    await timeout(1000);
    await job.load();
    }
    // job.result is a list of Collection instances
  • Creates a new ArangoDB user with the given password.

    Parameters

    • username: string

      Name of the ArangoDB user to create.

    • passwd: string

      Password of the new ArangoDB user.

    Returns Promise<ArangoApiResponse<ArangoUser>>

    Example

    const db = new Database();
    const user = await db.createUser("steve", "hunter2");
    // The user "steve" has been created
  • Creates a new ArangoDB user with the given options.

    Parameters

    • username: string

      Name of the ArangoDB user to create.

    • options: UserOptions

      Additional options for creating the ArangoDB user.

    Returns Promise<ArangoApiResponse<ArangoUser>>

    Example

    const db = new Database();
    const user = await db.createUser("steve", { passwd: "hunter2" });
    // The user "steve" has been created
  • Creates an AQL user function with the given name and code if it does not already exist or replaces it if a function with the same name already existed.

    Parameters

    • name: string

      A valid AQL function name. The function name must consist of at least two alphanumeric identifiers separated with double colons.

    • code: string

      A string evaluating to a JavaScript function (not a JavaScript function object).

    • isDeterministic: boolean = false

      If set to true, the function is expected to always return the same result for equivalent inputs. This option currently has no effect but may allow for optimizations in the future.

    Returns Promise<ArangoApiResponse<{
        isNewlyCreated: boolean;
    }>>

    Example

    const db = new Database();
    await db.createUserFunction(
    "ACME::ACCOUNTING::CALCULATE_VAT",
    "(price) => price * 0.19"
    );
    // Use the new function in an AQL query with template handler:
    const cursor = await db.query(aql`
    FOR product IN products
    RETURN MERGE(
    { vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price) },
    product
    )
    `);
    // cursor is a cursor for the query result
  • Creates a new View with the given viewName and options, then returns a views.View instance for the new View.

    Parameters

    • viewName: string

      Name of the View.

    • options: CreateViewOptions

      An object defining the properties of the View.

    Returns Promise<View>

    Example

    const db = new Database();
    const view = await db.createView("potatoes", { type: "arangosearch" });
    // the ArangoSearch View "potatoes" now exists
  • Creates a new Database instance for the given databaseName that shares this database's connection pool.

    See also :constructor.

    Parameters

    • databaseName: string

      Name of the database.

    Returns Database

    Example

    const systemDb = new Database();
    const myDb = systemDb.database("my_database");
  • Deletes the results of all completed async jobs.

    Returns Promise<void>

  • Deletes the results of all completed async jobs created before the given threshold.

    Parameters

    • threshold: number

      The expiration timestamp in milliseconds.

    Returns Promise<void>

    Example

    const db = new Database();
    const ONE_WEEK = 7 * 24 * 60 * 60 * 1000;
    await db.deleteExpiredJobResults(Date.now() - ONE_WEEK);
    // all job results older than a week have been deleted
  • (Enterprise Edition only.) Deletes a local hot backup.

    Parameters

    • id: string

      The ID of the backup to delete.

    Returns Promise<void>

    Example

    await db.deleteHotBackup("2023-09-19T15.38.21Z_example");
    // the backup has been deleted
  • Retrieves a zip bundle containing the service files.

    Returns a Buffer in node.js or Blob in the browser.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    Returns Promise<Buffer | Blob>

    Example

    const db = new Database();
    const serviceBundle = await db.downloadService("/my-foxx");
  • Deletes the database with the given databaseName from the server.

    Parameters

    • databaseName: string

      Name of the database to delete.

    Returns Promise<boolean>

    Example

    const db = new Database();
    await db.dropDatabase("mydb");
    // database "mydb" no longer exists
  • Deletes the AQL user function with the given name from the database.

    Parameters

    • name: string

      The name of the user function to drop.

    • group: boolean = false

      If set to true, all functions with a name starting with name will be deleted, otherwise only the function with the exact name will be deleted.

    Returns Promise<ArangoApiResponse<{
        deletedCount: number;
    }>>

    Example

    const db = new Database();
    await db.dropUserFunction("ACME::ACCOUNTING::CALCULATE_VAT");
    // the function no longer exists
  • Fetches storage engine information from the ArangoDB server.

    Returns Promise<EngineInfo>

    Example

    const db = new Database();
    const engine = await db.engine();
    // the engine object contains the storage engine information, e.g.
    // name: name of the storage engine
  • Fetches detailed storage engine performance and resource usage information from the ArangoDB server.

    Returns Promise<EngineStatsInfo>

    Example

    const db = new Database();
    const stats = await db.engineStats();
    // the stats object contains the storage engine stats
  • Executes the given cluster move shard operations.

    Parameters

    Returns Promise<unknown>

    Example

    const db = new Database();
    const result = await db.computerClusterRebalance({
    moveLeaders: true,
    moveFollowers: true
    });
    if (result.moves.length) {
    await db.executeClusterRebalance(result.moves);
    }
  • Performs a server-side JavaScript transaction and returns its return value.

    Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface: Collection, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.

    Note: The action function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via the params option.

    See the official ArangoDB documentation for the JavaScript @arangodb module for information about accessing the database from within ArangoDB's server-side JavaScript environment.

    Parameters

    • collections: TransactionCollectionOptions & {
          allowImplicit?: boolean;
      }

      Collections involved in the transaction.

    • action: string

      A string evaluating to a JavaScript function to be executed on the server.

    • Optional options: TransactionOptions & {
          params?: any;
      }

      Options for the transaction. If options.allowImplicit is specified, it will be used if collections.allowImplicit was not specified.

    Returns Promise<any>

    Example

    const db = new Database();

    const action = `
    function(params) {
    // This code will be executed inside ArangoDB!
    const { query } = require("@arangodb");
    return query\`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
    \`.toArray();
    }
    `);

    const result = await db.executeTransaction({
    read: ["_users"]
    }, action, {
    params: { age: 12 }
    });
    // result contains the return value of the action
  • Performs a server-side transaction and returns its return value.

    Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface: Collection, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.

    Note: The action function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via the params option. See the official ArangoDB documentation for the JavaScript @arangodb module for information about accessing the database from within ArangoDB's server-side JavaScript environment.

    Parameters

    • collections: (string | ArangoCollection)[]

      Collections that can be read from and written to during the transaction.

    • action: string

      A string evaluating to a JavaScript function to be executed on the server.

    • Optional options: TransactionOptions & {
          params?: any;
      }

      Options for the transaction.

    Returns Promise<any>

    Example

    const db = new Database();

    const action = `
    function(params) {
    // This code will be executed inside ArangoDB!
    const { query } = require("@arangodb");
    return query\`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
    \`.toArray();
    }
    `);

    const result = await db.executeTransaction(["_users"], action, {
    params: { age: 12 }
    });
    // result contains the return value of the action
  • Performs a server-side transaction and returns its return value.

    The Collection can be specified as a collection name (string) or an object implementing the collections.ArangoCollection interface: Collection, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.

    Note: The action function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via the params option. See the official ArangoDB documentation for the JavaScript @arangodb module for information about accessing the database from within ArangoDB's server-side JavaScript environment.

    Parameters

    • collection: string | ArangoCollection

      A collection that can be read from and written to during the transaction.

    • action: string

      A string evaluating to a JavaScript function to be executed on the server.

    • Optional options: TransactionOptions & {
          params?: any;
      }

      Options for the transaction.

    Returns Promise<any>

    Example

    const db = new Database();

    const action = `
    function(params) {
    // This code will be executed inside ArangoDB!
    const { query } = require("@arangodb");
    return query\`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
    \`.toArray();
    }
    `);

    const result = await db.executeTransaction("_users", action, {
    params: { age: 12 }
    });
    // result contains the return value of the action
  • Checks whether the database exists.

    Returns Promise<boolean>

    Example

    const db = new Database();
    const result = await db.exists();
    // result indicates whether the database exists
  • Explains a database query using the given query.

    See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Parameters

    • query: AqlQuery<any>

      An object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.

    • Optional options: ExplainOptions & {
          allPlans?: false;
      }

      Options for explaining the query.

    Returns Promise<ArangoApiResponse<SingleExplainResult>>

    Example

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(aql`
    FOR doc IN ${collection}
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `);
  • Explains a database query using the given query.

    See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Parameters

    • query: AqlQuery<any>

      An object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.

    • Optional options: ExplainOptions & {
          allPlans: true;
      }

      Options for explaining the query.

    Returns Promise<ArangoApiResponse<MultiExplainResult>>

    Example

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(
    aql`
    FOR doc IN ${collection}
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `,
    { allPlans: true }
    );
  • Explains a database query using the given query and bindVars.

    See the aql.aql template string handler for a safer and easier alternative to passing strings directly.

    Parameters

    • query: string | AqlLiteral

      An AQL query string.

    • Optional bindVars: Record<string, any>

      An object defining bind parameters for the query.

    • Optional options: ExplainOptions & {
          allPlans?: false;
      }

      Options for explaining the query.

    Returns Promise<ArangoApiResponse<SingleExplainResult>>

    Example

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(
    `
    FOR doc IN @@collection
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `,
    { "@collection": collection.name }
    );
  • Explains a database query using the given query and bindVars.

    See the aql.aql template string handler for a safer and easier alternative to passing strings directly.

    Parameters

    • query: string | AqlLiteral

      An AQL query string.

    • Optional bindVars: Record<string, any>

      An object defining bind parameters for the query.

    • Optional options: ExplainOptions & {
          allPlans: true;
      }

      Options for explaining the query.

    Returns Promise<ArangoApiResponse<MultiExplainResult>>

    Example

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(
    `
    FOR doc IN @@collection
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `,
    { "@collection": collection.name },
    { allPlans: true }
    );
  • (Enterprise Edition only.) Retrieves a list of all locally found hot backups.

    Parameters

    • Optional id: string | string[]

      If specified, only the backup with the given ID will be returned.

    Returns Promise<HotBackupList>

    Example

    const backups = await db.getHotBackups();
    for (const backup of backups.list) {
    console.log(backup.id);
    }
  • Retrieves the log messages from the server's global log.

    Parameters

    Returns Promise<LogEntries>

    Example

    const log = await db.getLogEntries();
    for (let i = 0; i < log.totalAmount; i++) {
    console.log(`${
    new Date(log.timestamp[i] * 1000).toISOString()
    } - [${LogLevel[log.level[i]]}] ${log.text[i]} (#${log.lid[i]})`);
    }
  • Retrieves the server's current log level for each topic.

    Returns Promise<Record<string, LogLevelSetting>>

    Example

    const levels = await db.getLogLevel();
    console.log(levels.request); // log level for incoming requests
  • Fetches the global properties for the AQL query results cache.

    Returns Promise<QueryCacheProperties>

    Example

    const db = new Database();
    const properties = await db.getQueryCacheProperties();
    console.log(properties);
  • Retrieves information about a mounted service.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    Returns Promise<ServiceDescription>

    Example

    const db = new Database();
    const info = await db.getService("/my-service");
    // info contains detailed information about the service
  • Retrieves information about the service's configuration options and their current values.

    See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • Optional minimal: false

      If set to true, the result will only include each configuration option's current value. Otherwise it will include the full definition for each option.

    Returns Promise<Record<string, ServiceConfiguration>>

    Example

    const db = new Database();
    const config = await db.getServiceConfiguration("/my-service");
    for (const [key, option] of Object.entries(config)) {
    console.log(`${option.title} (${key}): ${option.current}`);
    }
  • Retrieves information about the service's configuration options and their current values.

    See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • minimal: true

      If set to true, the result will only include each configuration option's current value. Otherwise it will include the full definition for each option.

    Returns Promise<Record<string, any>>

    Example

    const db = new Database();
    const config = await db.getServiceConfiguration("/my-service", true);
    for (const [key, value] of Object.entries(config)) {
    console.log(`${key}: ${value}`);
    }
  • Retrieves information about the service's dependencies and their current mount points.

    See also Database#replaceServiceDependencies and Database#updateServiceDependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • Optional minimal: false

      If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Returns Promise<Record<string, SingleServiceDependency | MultiServiceDependency>>

    Example

    const db = new Database();
    const deps = await db.getServiceDependencies("/my-service");
    for (const [key, dep] of Object.entries(deps)) {
    console.log(`${dep.title} (${key}): ${dep.current}`);
    }
  • Retrieves information about the service's dependencies and their current mount points.

    See also Database#replaceServiceDependencies and Database#updateServiceDependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • minimal: true

      If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Returns Promise<Record<string, string | string[]>>

    Example

    const db = new Database();
    const deps = await db.getServiceDependencies("/my-service", true);
    for (const [key, value] of Object.entries(deps)) {
    console.log(`${key}: ${value}`);
    }
  • Retrieves an Open API compatible Swagger API description object for the service installed at the given mount point.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    Returns Promise<SwaggerJson>

    Example

    const db = new Database();
    const spec = await db.getServiceDocumentation("/my-service");
    // spec is a Swagger API description of the service
  • Retrieves the text content of the service's README or README.md file.

    Returns undefined if no such file could be found.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    Returns Promise<undefined | string>

    Example

    const db = new Database();
    const readme = await db.getServiceReadme("/my-service");
    if (readme !== undefined) console.log(readme);
    else console.warn(`No README found.`)
  • Retrieves an object mapping script names to their human readable representations, as defined in the service manifest's "scripts" section.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    Returns Promise<Record<string, string>>

    Example

    const db = new Database();
    const scripts = await db.getServiceScripts("/my-service");
    for (const [name, title] of Object.entries(scripts)) {
    console.log(`${name}: ${title}`);
    }
  • Fetches the user data of a single ArangoDB user.

    Parameters

    • username: string

      Name of the ArangoDB user to fetch.

    Returns Promise<ArangoApiResponse<ArangoUser>>

    Example

    const db = new Database();
    const user = await db.getUser("steve");
    // user is the user object for the user named "steve"
  • Fetches the given ArangoDB user's access level for the database, or the given collection in the given database.

    Parameters

    • username: string

      Name of the ArangoDB user to fetch the access level for.

    • options: UserAccessLevelOptions

      Collection and/or database to fetch the access level for.

    Returns Promise<AccessLevel>

    Example

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve");
    // The access level of the user "steve" has been fetched for the current
    // database.

    Example

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve", {
    database: "staging"
    });
    // The access level of the user "steve" has been fetched for the "staging"
    // database.

    Example

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve", {
    collection: "pokemons"
    });
    // The access level of the user "steve" has been fetched for the
    // "pokemons" collection in the current database.

    Example

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve", {
    database: "staging",
    collection: "pokemons"
    });
    // The access level of the user "steve" has been fetched for the
    // "pokemons" collection in the "staging" database.

    Example

    const db = new Database();
    const staging = db.database("staging");
    const accessLevel = await db.getUserAccessLevel("steve", {
    database: staging
    });
    // The access level of the user "steve" has been fetched for the "staging"
    // database.

    Example

    const db = new Database();
    const staging = db.database("staging");
    const accessLevel = await db.getUserAccessLevel("steve", {
    collection: staging.collection("pokemons")
    });
    // The access level of the user "steve" has been fetched for the
    // "pokemons" collection in database "staging".
  • Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases.

    Parameters

    • username: string

      Name of the ArangoDB user to fetch the access levels for.

    • Optional full: false

      Whether access levels for collections should be included.

    Returns Promise<Record<string, AccessLevel>>

    Example

    const db = new Database();
    const accessLevels = await db.getUserDatabases("steve");
    for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {
    console.log(`${databaseName}: ${accessLevel}`);
    }
  • Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases and the collections within each database.

    Parameters

    • username: string

      Name of the ArangoDB user to fetch the access levels for.

    • full: true

      Whether access levels for collections should be included.

    Returns Promise<Record<string, {
        collections: Record<string, "undefined" | AccessLevel>;
        permission: AccessLevel;
    }>>

    Example

    const db = new Database();
    const accessLevels = await db.getUserDatabases("steve", true);
    for (const [databaseName, obj] of Object.entries(accessLevels)) {
    console.log(`${databaseName}: ${obj.permission}`);
    for (const [collectionName, accessLevel] of Object.entries(obj.collections)) {
    console.log(`${databaseName}/${collectionName}: ${accessLevel}`);
    }
    }
  • Returns a graphs.Graph instance representing the graph with the given graphName.

    Parameters

    • graphName: string

      Name of the graph.

    Returns Graph

    Example

    const db = new Database();
    const graph = db.graph("some-graph");
  • Fetches all graphs from the database and returns an array of graphs.Graph instances for those graphs.

    See also Database#listGraphs.

    Returns Promise<Graph[]>

    Example

    const db = new Database();
    const graphs = await db.graphs();
    // graphs is an array of Graph instances
  • Installs a new service.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • source: string | Blob | File

      The service bundle to install.

    • options: InstallServiceOptions = {}

      Options for installing the service.

    Returns Promise<ServiceDescription>

    Example

    const db = new Database();
    // Using a Buffer in Node.js as source
    const source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);
    const info = await db.installService("/hello", source);

    Example

    const db = new Database();
    // Using a Blob in Node.js as source
    const source = await fs.openAsBlob("./my-foxx-service.zip");
    const info = await db.installService("/hello", source);

    Example

    const db = new Database();
    // Using a File from a browser file input as source
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.installService("/hello", source);
  • Returns a jobs.Job instance for the given jobId.

    Parameters

    • jobId: string

      ID of the async job.

    Returns Job<any>

    Example

    const db = new Database();
    const job = db.job("12345");
  • Kills a running query with the given queryId.

    See also Database#listRunningQueries.

    Parameters

    • queryId: string

      The ID of a currently running query.

    Returns Promise<void>

    Example

    const db = new Database();
    const queries = await db.listRunningQueries();
    await Promise.all(queries.map(
    async (query) => {
    if (query.state === "executing") {
    await db.killQuery(query.id);
    }
    }
    ));
  • Fetches all Analyzers visible in the database and returns an array of Analyzer descriptions.

    See also Database#analyzers.

    Returns Promise<AnalyzerDescription[]>

    Example

    const db = new Database();
    const analyzers = await db.listAnalyzers();
    // analyzers is an array of Analyzer descriptions
  • Fetches all collections from the database and returns an array of collection descriptions.

    See also Database#collections.

    Parameters

    • excludeSystem: boolean = true

      Whether system collections should be excluded.

    Returns Promise<CollectionDescription[]>

    Example

    const db = new Database();
    const collections = await db.listCollections();
    // collections is an array of collection descriptions
    // not including system collections

    Example

    const db = new Database();
    const collections = await db.listCollections(false);
    // collections is an array of collection descriptions
    // including system collections
  • Returns a list of the IDs of all currently available completed async jobs.

    Returns Promise<string[]>

    Example

    const db = new Database();
    const completedJobs = await db.listCompletedJobs();
    console.log(completedJobs); // e.g. ["12345", "67890"]
  • Fetches all databases from the server and returns an array of their names.

    See also Database#databases and Database#listUserDatabases.

    Returns Promise<string[]>

    Example

    const db = new Database();
    const names = await db.listDatabases();
    // databases is an array of database names
  • Fetches all graphs from the database and returns an array of graph descriptions.

    See also Database#graphs.

    Returns Promise<GraphDescription[]>

    Example

    const db = new Database();
    const graphs = await db.listGraphs();
    // graphs is an array of graph descriptions
  • Retrieves the log messages from the server's global log.

    Parameters

    Returns Promise<LogMessage[]>

    Deprecated

    This endpoint has been deprecated in ArangoDB 3.8. Use Database#getLogEntries instead.

    Example

    const messages = await db.listLogMessages();
    for (const m of messages) {
    console.log(`${m.date} - [${m.level}] ${m.message} (#${m.id})`);
    }
  • Returns a list of the IDs of all currently pending async jobs.

    Returns Promise<string[]>

    Example

    const db = new Database();
    const pendingJobs = await db.listPendingJobs();
    console.log(pendingJobs); // e.g. ["12345", "67890"]
  • Fetches a list of all entries in the AQL query results cache of the current database.

    Returns Promise<QueryCacheEntry[]>

    Example

    const db = new Database();
    const entries = await db.listQueryCacheEntries();
    console.log(entries);
  • Fetches a list of all installed service.

    Parameters

    • excludeSystem: boolean = true

      Whether system services should be excluded.

    Returns Promise<ServiceSummary[]>

    Example

    const db = new Database();
    const services = await db.listServices();

    Example

    const db = new Database();
    const services = await db.listServices(false); // all services
  • Fetches all databases accessible to the active user from the server and returns an array of their names.

    See also Database#userDatabases and Database#listDatabases.

    Returns Promise<string[]>

    Example

    const db = new Database();
    const names = await db.listUserDatabases();
    // databases is an array of database names
  • Fetches a list of all AQL user functions registered with the database.

    Returns Promise<UserFunctionDescription[]>

    Example

    const db = new Database();
    const functions = await db.listUserFunctions();
    const names = functions.map(fn => fn.name);
  • Fetches all ArangoDB users visible to the authenticated user and returns an array of user objects.

    Returns Promise<ArangoUser[]>

    Example

    const db = new Database();
    const users = await db.listUsers();
    // users is an array of user objects
  • Fetches all Views from the database and returns an array of View descriptions.

    See also Database#views.

    Returns Promise<ViewDescription[]>

    Example

    const db = new Database();

    const views = await db.listViews();
    // views is an array of View descriptions
  • Validates the given database credentials and exchanges them for an authentication token, then uses the authentication token for future requests and returns it.

    Parameters

    • username: string = "root"

      The username to authenticate with.

    • password: string = ""

      The password to authenticate with.

    Returns Promise<string>

    Example

    const db = new Database();
    await db.login("admin", "hunter2");
    // with an authentication token for the "admin" user.
  • Parses the given query and returns the result.

    See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Parameters

    • query: string | AqlLiteral | AqlQuery<any>

      An AQL query string or an object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.

    Returns Promise<ParseResult>

    Example

    const db = new Database();
    const collection = db.collection("some-collection");
    const ast = await db.parse(aql`
    FOR doc IN ${collection}
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `);

    aql.

  • Performs a database query using the given query, then returns a new cursors.Cursor instance for the result set.

    See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Note: When executing a query in a streaming transaction using the step method, the resulting cursor will be bound to that transaction and you do not need to use the step method to consume it.

    Type Parameters

    • T = any

    Parameters

    • query: AqlQuery<T>

      An object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.

    • Optional options: QueryOptions

      Options for the query execution.

    Returns Promise<Cursor<T>>

    Example

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");

    // Using an aql template string:
    // Bind parameters are automatically extracted and arangojs collections
    // are automatically passed as collection bind parameters.
    const cursor = await db.query(aql`
    FOR u IN ${Users}
    FILTER u.authData.active == ${active}
    RETURN u.user
    `);
    // cursor is a cursor for the query result

    Example

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");

    // Using an object with a regular multi-line string
    const cursor = await db.query({
    query: `
    FOR u IN @@users
    FILTER u.authData.active == @active
    RETURN u.user
    `,
    bindVars: { active: active, "@users": Users.name }
    });
  • Performs a database query using the given query and bindVars, then returns a new cursors.Cursor instance for the result set.

    See the aql.aql template string handler for a safer and easier alternative to passing strings directly.

    Note: When executing a query in a streaming transaction using the step method, the resulting cursor will be bound to that transaction and you do not need to use the step method to consume it.

    Type Parameters

    • T = any

    Parameters

    • query: string | AqlLiteral

      An AQL query string.

    • Optional bindVars: Record<string, any>

      An object defining bind parameters for the query.

    • Optional options: QueryOptions

      Options for the query execution.

    Returns Promise<Cursor<T>>

    Example

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");

    const cursor = await db.query(
    // A normal multi-line string
    `
    FOR u IN @@users
    FILTER u.authData.active == @active
    RETURN u.user
    `,
    { active: active, "@users": Users.name }
    );

    Example

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");

    const cursor = await db.query(
    // An AQL literal created from a normal multi-line string
    aql.literal(`
    FOR u IN @@users
    FILTER u.authData.active == @active
    RETURN u.user
    `),
    { active: active, "@users": Users.name }
    );
  • Fetches the available optimizer rules.

    Returns Promise<QueryOptimizerRule[]>

    Example

    const db = new Database();
    const rules = await db.queryRules();
    for (const rule of rules) {
    console.log(rule.name);
    }
  • Fetches the query tracking properties.

    Returns Promise<QueryTrackingInfo>

    Example

    const db = new Database();
    const tracking = await db.queryTracking();
    console.log(tracking.enabled);
  • Modifies the query tracking properties.

    Parameters

    Returns Promise<QueryTrackingInfo>

    Example

    const db = new Database();
    // track up to 5 slow queries exceeding 5 seconds execution time
    await db.setQueryTracking({
    enabled: true,
    trackSlowQueries: true,
    maxSlowQueries: 5,
    slowQueryThreshold: 5
    });
  • Computes a set of move shard operations to rebalance the cluster and executes them.

    Parameters

    Returns Promise<ClusterRebalanceResult>

    Example

    const db = new Database();
    const result = await db.rebalanceCluster({
    moveLeaders: true,
    moveFollowers: true
    });
    // The cluster is now rebalanced.
  • Removes the ArangoDB user with the given username from the server.

    Parameters

    • username: string

      Name of the ArangoDB user to remove.

    Returns Promise<void>

    Example

    const db = new Database();
    await db.removeUser("steve");
    // The user "steve" has been removed
  • Renames the collection collectionName to newName.

    Additionally removes any stored Collection instance for collectionName from the Database instance's internal cache.

    Note: Renaming collections may not be supported when ArangoDB is running in a cluster configuration.

    Parameters

    • collectionName: string

      Current name of the collection.

    • newName: string

      The new name of the collection.

    Returns Promise<ArangoApiResponse<CollectionDescription>>

  • Renames the view viewName to newName.

    Additionally removes any stored views.View instance for viewName from the Database instance's internal cache.

    Note: Renaming views may not be supported when ArangoDB is running in a cluster configuration.

    Parameters

    • viewName: string

      Current name of the view.

    • newName: string

      The new name of the view.

    Returns Promise<ArangoApiResponse<ViewDescription>>

  • Attempts to renew the authentication token passed to Database#useBearerAuth or returned and used by Database#login. If a new authentication token is issued, it will be used for future requests and returned.

    Returns Promise<null | string>

    Example

    const db = new Database();
    await db.login("admin", "hunter2");
    // ... later ...
    const newToken = await db.renewAuthToken();
    if (!newToken) // no new token issued
  • Replaces an existing service with a new service by completely removing the old service and installing a new service at the same mount point.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • source: string | Blob | File

      The service bundle to install.

    • options: ReplaceServiceOptions = {}

      Options for replacing the service.

    Returns Promise<ServiceDescription>

    Example

    const db = new Database();
    // Using a Buffer in Node.js as source
    const source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);
    const info = await db.replaceService("/hello", source);

    Example

    const db = new Database();
    // Using a Blob in Node.js as source
    const source = await fs.openAsBlob("./my-foxx-service.zip");
    const info = await db.replaceService("/hello", source);

    Example

    const db = new Database();
    // Using a File from a browser file input as source
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.replaceService("/hello", source);
  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also Database#updateServiceConfiguration and Database#getServiceConfiguration.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • cfg: Record<string, any>

      An object mapping configuration option names to values.

    • Optional minimal: false

      If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Returns Promise<Record<string, ServiceConfiguration & {
        warning?: string;
    }>>

    Example

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.replaceServiceConfiguration("/my-service", config);
    for (const [key, option] of Object.entries(info)) {
    console.log(`${option.title} (${key}): ${option.value}`);
    if (option.warning) console.warn(`Warning: ${option.warning}`);
    }
  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also Database#updateServiceConfiguration and Database#getServiceConfiguration.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • cfg: Record<string, any>

      An object mapping configuration option names to values.

    • minimal: true

      If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Returns Promise<{
        values: Record<string, any>;
        warnings: Record<string, string>;
    }>

    Example

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.replaceServiceConfiguration("/my-service", config);
    for (const [key, value] of Object.entries(info.values)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }
  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also Database#updateServiceDependencies and Database#getServiceDependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • deps: Record<string, string>

      An object mapping dependency aliases to mount points.

    • Optional minimal: false

      If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Returns Promise<Record<string, (SingleServiceDependency | MultiServiceDependency) & {
        warning?: string;
    }>>

    Example

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.replaceServiceDependencies("/my-service", deps);
    for (const [key, dep] of Object.entries(info)) {
    console.log(`${dep.title} (${key}): ${dep.current}`);
    if (dep.warning) console.warn(`Warning: ${dep.warning}`);
    }
  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also Database#updateServiceDependencies and Database#getServiceDependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • deps: Record<string, string>

      An object mapping dependency aliases to mount points.

    • minimal: true

      If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Returns Promise<{
        values: Record<string, string>;
        warnings: Record<string, string>;
    }>

    Example

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.replaceServiceDependencies(
    "/my-service",
    deps,
    true
    );
    for (const [key, value] of Object.entries(info)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }
  • Replaces the ArangoDB user's option with the new options.

    Parameters

    • username: string

      Name of the ArangoDB user to modify.

    • options: UserOptions

      New options to replace the user's existing options.

    Returns Promise<ArangoApiResponse<ArangoUser>>

    Example

    const db = new Database();
    const user = await db.replaceUser("steve", { passwd: "", active: false });
    // The user "steve" has been set to inactive with an empty password
  • (Enteprise Edition only.) Restores a consistent local hot backup.

    Returns the directory path of the restored backup.

    Parameters

    • id: string

      The ID of the backup to restore.

    Returns Promise<string>

    Example

    await db.restoreHotBackup("2023-09-19T15.38.21Z_example");
    // the backup has been restored
  • Returns a new routes.Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.

    Parameters

    • Optional path: string

      The database-relative URL of the route. Defaults to the database API root.

    • Optional headers: Record<string, string> | Headers

      Default headers that should be sent with each request to the route.

    Returns Route

    Example

    const db = new Database();
    const myFoxxService = db.route("my-foxx-service");
    const response = await myFoxxService.post("users", {
    username: "admin",
    password: "hunter2"
    });
    // response.body is the result of
    // POST /_db/_system/my-foxx-service/users
    // with JSON request body '{"username": "admin", "password": "hunter2"}'
  • Executes a service script and retrieves its result exposed as module.exports (if any).

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • name: string

      Name of the service script to execute as defined in the service manifest.

    • Optional params: any

      Arbitrary value that will be exposed to the script as argv[0] in the service context (e.g. module.context.argv[0]). Must be serializable to JSON.

    Returns Promise<any>

    Example

    const db = new Database();
    const result = await db.runServiceScript(
    "/my-service",
    "create-user",
    {
    username: "service_admin",
    password: "hunter2"
    }
    );
  • Runs the tests of a given service and returns the results using the "default" reporter.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • Optional options: {
          filter?: string;
          idiomatic?: false;
          reporter?: "default";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • Optional idiomatic?: false

        Whether the reporter should use "idiomatic" mode. Has no effect when using the "default" or "suite" reporters.

      • Optional reporter?: "default"

    Returns Promise<ServiceTestDefaultReport>

    Example

    const db = new Database();
    const testReport = await db.runServiceTests("/my-foxx");
  • Runs the tests of a given service and returns the results using the "suite" reporter, which groups the test result by test suite.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic?: false;
          reporter: "suite";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • Optional idiomatic?: false

        Whether the reporter should use "idiomatic" mode. Has no effect when using the "default" or "suite" reporters.

      • reporter: "suite"

    Returns Promise<ServiceTestSuiteReport>

    Example

    const db = new Database();
    const suiteReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "suite" }
    );
  • Runs the tests of a given service and returns the results using the "stream" reporter, which represents the results as a sequence of tuples representing events.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic?: false;
          reporter: "stream";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • Optional idiomatic?: false

        Whether the reporter should use "idiomatic" mode. If set to true, the results will be returned as a formatted string.

      • reporter: "stream"

    Returns Promise<ServiceTestStreamReport>

    Example

    const db = new Database();
    const streamEvents = await db.runServiceTests(
    "/my-foxx",
    { reporter: "stream" }
    );
  • Runs the tests of a given service and returns the results using the "tap" reporter, which represents the results as an array of strings using the "tap" format.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic?: false;
          reporter: "tap";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • Optional idiomatic?: false

        Whether the reporter should use "idiomatic" mode. If set to true, the results will be returned as a formatted string.

      • reporter: "tap"

    Returns Promise<ServiceTestTapReport>

    Example

    const db = new Database();
    const tapLines = await db.runServiceTests(
    "/my-foxx",
    { reporter: "tap" }
    );
  • Runs the tests of a given service and returns the results using the "xunit" reporter, which represents the results as an XML document using the JSONML exchange format.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic?: false;
          reporter: "xunit";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • Optional idiomatic?: false

        Whether the reporter should use "idiomatic" mode. If set to true, the results will be returned as a formatted string.

      • reporter: "xunit"

    Returns Promise<ServiceTestXunitReport>

    Example

    const db = new Database();
    const jsonML = await db.runServiceTests(
    "/my-foxx",
    { reporter: "xunit" }
    );
  • Runs the tests of a given service and returns the results as a string using the "stream" reporter in "idiomatic" mode, which represents the results as a line-delimited JSON stream of tuples representing events.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic: true;
          reporter: "stream";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • idiomatic: true

        Whether the reporter should use "idiomatic" mode. If set to false, the results will be returned as an array of tuples instead of a string.

      • reporter: "stream"

    Returns Promise<string>

    Example

    const db = new Database();
    const streamReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "stream", idiomatic: true }
    );
  • Runs the tests of a given service and returns the results as a string using the "tap" reporter in "idiomatic" mode, which represents the results using the "tap" format.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic: true;
          reporter: "tap";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • idiomatic: true

        Whether the reporter should use "idiomatic" mode. If set to false, the results will be returned as an array of strings instead of a single string.

      • reporter: "tap"

    Returns Promise<string>

    Example

    const db = new Database();
    const tapReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "tap", idiomatic: true }
    );
  • Runs the tests of a given service and returns the results as a string using the "xunit" reporter in "idiomatic" mode, which represents the results as an XML document.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • options: {
          filter?: string;
          idiomatic: true;
          reporter: "xunit";
      }

      Options for running the tests.

      • Optional filter?: string

        If set, only tests with full names including this exact string will be executed.

      • idiomatic: true

        Whether the reporter should use "idiomatic" mode. If set to false, the results will be returned using the JSONML exchange format instead of a string.

      • reporter: "xunit"

    Returns Promise<string>

    Example

    const db = new Database();
    const xml = await db.runServiceTests(
    "/my-foxx",
    { reporter: "xunit", idiomatic: true }
    );
  • Set a new license for an Enterprise Edition server.

    Parameters

    • license: string

      The license as a base 64 encoded string.

    • force: boolean = false

      If set to true, the license will be changed even if it expires sooner than the current license.

    Returns Promise<void>

  • Sets the server's log level for each of the given topics to the given level.

    Any omitted topics will be left unchanged.

    Parameters

    • levels: Record<string, LogLevelSetting>

      An object mapping topic names to log levels.

    Returns Promise<Record<string, LogLevelSetting>>

    Example

    await db.setLogLevel({ request: "debug" });
    // Debug information will now be logged for each request
  • Sets the limit for the number of values of the most recently received server-reported queue times that can be accessed using Database#queueTime.

    Parameters

    • responseQueueTimeSamples: number

      Number of values to maintain.

    Returns void

  • Enables or disables development mode for the given service.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • enabled: boolean = true

      Whether development mode should be enabled or disabled.

    Returns Promise<ServiceDescription>

    Example

    const db = new Database();
    await db.setServiceDevelopmentMode("/my-service", true);
    // the service is now in development mode
    await db.setServiceDevelopmentMode("/my-service", false);
    // the service is now in production mode
  • Sets the given ArangoDB user's access level for the database, or the given collection in the given database.

    Parameters

    • username: string

      Name of the ArangoDB user to set the access level for.

    • options: UserAccessLevelOptions

      Database and/or collection to set the access level for.

    • grant: AccessLevel

      Access level to set for the given user.

    Returns Promise<ArangoApiResponse<Record<string, AccessLevel>>>

    Example

    const db = new Database();
    await db.setUserAccessLevel("steve", { grant: "rw" });
    // The user "steve" now has read-write access to the current database.

    Example

    const db = new Database();
    await db.setUserAccessLevel("steve", {
    database: "staging",
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "staging" database.

    Example

    const db = new Database();
    await db.setUserAccessLevel("steve", {
    collection: "pokemons",
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "pokemons" collection
    // in the current database.

    Example

    const db = new Database();
    await db.setUserAccessLevel("steve", {
    database: "staging",
    collection: "pokemons",
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "pokemons" collection
    // in the "staging" database.

    Example

    const db = new Database();
    const staging = db.database("staging");
    await db.setUserAccessLevel("steve", {
    database: staging,
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "staging" database.

    Example

    const db = new Database();
    const staging = db.database("staging");
    await db.setUserAccessLevel("steve", {
    collection: staging.collection("pokemons"),
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "pokemons" collection
    // in database "staging".
  • Attempts to initiate a clean shutdown of the server.

    Returns Promise<void>

  • Fetches information about the server status.

    Returns Promise<ServerStatusInfo>

    Example

    const status = await db.status();
    // the status object contains the ArangoDB status information, e.g.
    // version: ArangoDB version number
    // host: host identifier of the server
    // serverInfo: detailed information about the server
  • Retrives the server's current system time in milliseconds with microsecond precision.

    Returns Promise<number>

  • Returns a transactions.Transaction instance for an existing streaming transaction with the given id.

    See also Database#beginTransaction.

    Parameters

    • transactionId: string

      The id of an existing stream transaction.

    Returns Transaction

    Example

    const trx1 = await db.beginTransaction(collections);
    const id = trx1.id;
    // later
    const trx2 = db.transaction(id);
    await trx2.commit();
  • Completely removes a service from the database.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • Optional options: UninstallServiceOptions

      Options for uninstalling the service.

    Returns Promise<void>

    Example

    const db = new Database();
    await db.uninstallService("/my-foxx");
  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • cfg: Record<string, any>

      An object mapping configuration option names to values.

    • Optional minimal: false

      If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Returns Promise<Record<string, ServiceConfiguration & {
        warning?: string;
    }>>

    Example

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.updateServiceConfiguration("/my-service", config);
    for (const [key, option] of Object.entries(info)) {
    console.log(`${option.title} (${key}): ${option.value}`);
    if (option.warning) console.warn(`Warning: ${option.warning}`);
    }
  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • cfg: Record<string, any>

      An object mapping configuration option names to values.

    • minimal: true

      If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Returns Promise<{
        values: Record<string, any>;
        warnings: Record<string, string>;
    }>

    Example

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.updateServiceConfiguration("/my-service", config);
    for (const [key, value] of Object.entries(info.values)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }
  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also Database#replaceServiceDependencies and Database#getServiceDependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • deps: Record<string, string>

      An object mapping dependency aliases to mount points.

    • Optional minimal: false

      If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Returns Promise<Record<string, (SingleServiceDependency | MultiServiceDependency) & {
        warning?: string;
    }>>

    Example

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.updateServiceDependencies("/my-service", deps);
    for (const [key, dep] of Object.entries(info)) {
    console.log(`${dep.title} (${key}): ${dep.current}`);
    if (dep.warning) console.warn(`Warning: ${dep.warning}`);
    }
  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also Database#replaceServiceDependencies and Database#getServiceDependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • deps: Record<string, string>

      An object mapping dependency aliases to mount points.

    • minimal: true

      If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Returns Promise<{
        values: Record<string, string>;
        warnings: Record<string, string>;
    }>

    Example

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.updateServiceDependencies(
    "/my-service",
    deps,
    true
    );
    for (const [key, value] of Object.entries(info)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }
  • Sets the password of a given ArangoDB user to the new value.

    Parameters

    • username: string

      Name of the ArangoDB user to change the password for.

    • passwd: string

      New password for the ArangoDB user.

    Returns Promise<ArangoApiResponse<ArangoUser>>

    Example

    const db = new Database();
    const user = await db.updateUser("steve", "hunter2");
    // The user "steve" has received a new password
  • Updates the ArangoDB user with the new options.

    Parameters

    • username: string

      Name of the ArangoDB user to modify.

    • options: Partial<UserOptions>

      Options of the ArangoDB user to modify.

    Returns Promise<ArangoApiResponse<ArangoUser>>

    Example

    const db = new Database();
    const user = await db.updateUser("steve", { active: false });
    // The user "steve" has been set to inactive
  • Replaces an existing service with a new service while retaining the old service's configuration and dependencies.

    Parameters

    • mount: string

      The service's mount point, relative to the database.

    • source: string | Blob | File

      The service bundle to install.

    • options: UpgradeServiceOptions = {}

      Options for upgrading the service.

    Returns Promise<ServiceDescription>

    Example

    const db = new Database();
    // Using a Buffer in Node.js as source
    const source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);
    const info = await db.upgradeService("/hello", source);

    Example

    const db = new Database();
    // Using a Blob in Node.js as source
    const source = await fs.openAsBlob("./my-foxx-service.zip");
    const info = await db.upgradeService("/hello", source);

    Example

    const db = new Database();
    // Using a File from a browser file input as source
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.upgradeService("/hello", source);
  • Updates the underlying connection's authorization header to use Basic authentication with the given username and password, then returns itself.

    Parameters

    • username: string = "root"

      The username to authenticate with.

    • password: string = ""

      The password to authenticate with.

    Returns this

    Example

    const db = new Database();
    db.useBasicAuth("admin", "hunter2");
    // with the username "admin" and password "hunter2".
  • Updates the underlying connection's authorization header to use Bearer authentication with the given authentication token, then returns itself.

    Parameters

    • token: string

      The token to authenticate with.

    Returns this

    Example

    const db = new Database();
    db.useBearerAuth("keyboardcat");
    // The database instance now uses Bearer authentication.
  • Fetches all databases accessible to the active user from the server and returns an array of Database instances for those databases.

    See also Database#listUserDatabases and Database#databases.

    Returns Promise<Database[]>

    Example

    const db = new Database();
    const names = await db.userDatabases();
    // databases is an array of databases
  • Fetches version information from the ArangoDB server.

    Parameters

    • Optional details: boolean

      If set to true, additional information about the ArangoDB server will be available as the details property.

    Returns Promise<VersionInfo>

    Example

    const db = new Database();
    const version = await db.version();
    // the version object contains the ArangoDB version information.
    // license: "community" or "enterprise"
    // version: ArangoDB version number
    // server: description of the server
  • Returns a views.View instance for the given viewName.

    Parameters

    • viewName: string

      Name of the ArangoSearch or SearchAlias View.

    Returns View

    Example

    const db = new Database();
    const view = db.view("potatoes");
  • Fetches all Views from the database and returns an array of views.View instances for the Views.

    See also Database#listViews.

    Returns Promise<View[]>

    Example

    const db = new Database();
    const views = await db.views();
    // views is an array of ArangoSearch View instances
  • Performs a request against every known coordinator and returns when the request has succeeded against every coordinator or the timeout is reached.

    Note: This method is primarily intended to make database setup easier in cluster scenarios and requires all coordinators to be known to arangojs before the method is invoked. The method is not useful in single-server or leader-follower replication scenarios.

    Parameters

    • request: RequestOptions

      Request to perform against each known coordinator.

    • Optional timeout: number

      Maximum number of milliseconds to wait for propagation.

    Returns Promise<void>

    Example

    const db = new Database({ loadBalancingStrategy: "ROUND_ROBIN" });
    await system.acquireHostList();
    const analyzer = db.analyzer("my-analyzer");
    await analyzer.create();
    await db.waitForPropagation(
    { pathname: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },
    30000
    );
    // Analyzer has been propagated to all coordinators and can safely be used
  • Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.

    Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface: Collection, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.

    Type Parameters

    • T

    Parameters

    • collections: TransactionCollectionOptions

      Collections involved in the transaction.

    • callback: ((step) => Promise<T>)

      Callback function executing the transaction steps.

        • (step): Promise<T>
        • Parameters

          • step: (<T>(callback) => Promise<T>)
              • <T>(callback): Promise<T>
              • Executes the given function locally as a single step of the transaction.

                Type Parameters

                • T

                  Type of the callback's returned promise.

                Parameters

                • callback: (() => Promise<T>)

                  Callback function returning a promise.

                  Warning: The callback function should wrap a single call of an async arangojs method (e.g. a method on a Collection object of a collection that is involved in the transaction or the db.query method). If the callback function is async, only the first promise-returning (or async) method call will be executed as part of the transaction. See the examples below for how to avoid common mistakes when using this method.

                  Note: Avoid defining the callback as an async function if possible as arangojs will throw an error if the callback did not return a promise. Async functions will return an empty promise by default, making it harder to notice if you forgot to return something from the callback.

                  Note: Although almost anything can be wrapped in a callback and passed to this method, that does not guarantee ArangoDB can actually do it in a transaction. Refer to the ArangoDB documentation if you are unsure whether a given operation can be executed as part of a transaction. Generally any modification or retrieval of data is eligible but modifications of collections or databases are not.

                    • (): Promise<T>
                    • Returns Promise<T>

                Returns Promise<T>

                Example

                const db = new Database();
                const vertices = db.collection("vertices");
                const edges = db.collection("edges");
                const trx = await db.beginTransaction({ write: [vertices, edges] });

                // The following code will be part of the transaction
                const left = await trx.step(() => vertices.save({ label: "left" }));
                const right = await trx.step(() => vertices.save({ label: "right" }));

                // Results from preceding actions can be used normally
                await trx.step(() => edges.save({
                _from: left._id,
                _to: right._id,
                data: "potato"
                }));

                // Transaction must be committed for changes to take effected
                // Always call either trx.commit or trx.abort to end a transaction
                await trx.commit();

                Example

                // BAD! If the callback is an async function it must only use await once!
                await trx.step(async () => {
                await collection.save(data);
                await collection.save(moreData); // WRONG
                });

                // BAD! Callback function must use only one arangojs call!
                await trx.step(() => {
                return collection.save(data)
                .then(() => collection.save(moreData)); // WRONG
                });

                // BETTER: Wrap every arangojs method call that should be part of the
                // transaction in a separate `trx.step` call
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));

                Example

                // BAD! If the callback is an async function it must not await before
                // calling an arangojs method!
                await trx.step(async () => {
                await doSomethingElse();
                return collection.save(data); // WRONG
                });

                // BAD! Any arangojs inside the callback must not happen inside a promise
                // method!
                await trx.step(() => {
                return doSomethingElse()
                .then(() => collection.save(data)); // WRONG
                });

                // BETTER: Perform any async logic needed outside the `trx.step` call
                await doSomethingElse();
                await trx.step(() => collection.save(data));

                // OKAY: You can perform async logic in the callback after the arangojs
                // method call as long as it does not involve additional arangojs method
                // calls, but this makes it easy to make mistakes later
                await trx.step(async () => {
                await collection.save(data);
                await doSomethingDifferent(); // no arangojs method calls allowed
                });

                Example

                // BAD! The callback should not use any functions that themselves use any
                // arangojs methods!
                async function saveSomeData() {
                await collection.save(data);
                await collection.save(moreData);
                }
                await trx.step(() => saveSomeData()); // WRONG

                // BETTER: Pass the transaction to functions that need to call arangojs
                // methods inside a transaction
                async function saveSomeData(trx) {
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));
                }
                await saveSomeData(); // no `trx.step` call needed

                Example

                // BAD! You must wait for the promise to resolve (or await on the
                // `trx.step` call) before calling `trx.step` again!
                trx.step(() => collection.save(data)); // WRONG
                await trx.step(() => collection.save(moreData));

                // BAD! The trx.step callback can not make multiple calls to async arangojs
                // methods, not even using Promise.all!
                await trx.step(() => Promise.all([ // WRONG
                collection.save(data),
                collection.save(moreData),
                ]));

                // BAD! Multiple `trx.step` calls can not run in parallel!
                await Promise.all([ // WRONG
                trx.step(() => collection.save(data)),
                trx.step(() => collection.save(moreData)),
                ]));

                // BETTER: Always call `trx.step` sequentially, one after the other
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));

                // OKAY: The then callback can be used if async/await is not available
                trx.step(() => collection.save(data))
                .then(() => trx.step(() => collection.save(moreData)));

                Example

                // BAD! The callback will return an empty promise that resolves before
                // the inner arangojs method call has even talked to ArangoDB!
                await trx.step(async () => {
                collection.save(data); // WRONG
                });

                // BETTER: Use an arrow function so you don't forget to return
                await trx.step(() => collection.save(data));

                // OKAY: Remember to always return when using a function body
                await trx.step(() => {
                return collection.save(data); // easy to forget!
                });

                // OKAY: You do not have to use arrow functions but it helps
                await trx.step(function () {
                return collection.save(data);
                });

                Example

                // BAD! You can not pass promises instead of a callback!
                await trx.step(collection.save(data)); // WRONG

                // BETTER: Wrap the code in a function and pass the function instead
                await trx.step(() => collection.save(data));

                Example

                // WORSE: Calls to non-async arangojs methods don't need to be performed
                // as part of a transaction
                const collection = await trx.step(() => db.collection("my-documents"));

                // BETTER: If an arangojs method is not async and doesn't return promises,
                // call it without `trx.step`
                const collection = db.collection("my-documents");

          Returns Promise<T>

    • Optional options: TransactionOptions

      Options for the transaction.

    Returns Promise<T>

    Example

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    await db.withTransaction(
    {
    read: ["vertices"],
    write: [edges] // collection instances can be passed directly
    },
    async (step) => {
    const start = await step(() => vertices.document("a"));
    const end = await step(() => vertices.document("b"));
    await step(() => edges.save({ _from: start._id, _to: end._id }));
    }
    );
  • Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.

    Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface: Collection, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.

    Type Parameters

    • T

    Parameters

    • collections: (string | ArangoCollection)[]

      Collections that can be read from and written to during the transaction.

    • callback: ((step) => Promise<T>)

      Callback function executing the transaction steps.

        • (step): Promise<T>
        • Parameters

          • step: (<T>(callback) => Promise<T>)
              • <T>(callback): Promise<T>
              • Executes the given function locally as a single step of the transaction.

                Type Parameters

                • T

                  Type of the callback's returned promise.

                Parameters

                • callback: (() => Promise<T>)

                  Callback function returning a promise.

                  Warning: The callback function should wrap a single call of an async arangojs method (e.g. a method on a Collection object of a collection that is involved in the transaction or the db.query method). If the callback function is async, only the first promise-returning (or async) method call will be executed as part of the transaction. See the examples below for how to avoid common mistakes when using this method.

                  Note: Avoid defining the callback as an async function if possible as arangojs will throw an error if the callback did not return a promise. Async functions will return an empty promise by default, making it harder to notice if you forgot to return something from the callback.

                  Note: Although almost anything can be wrapped in a callback and passed to this method, that does not guarantee ArangoDB can actually do it in a transaction. Refer to the ArangoDB documentation if you are unsure whether a given operation can be executed as part of a transaction. Generally any modification or retrieval of data is eligible but modifications of collections or databases are not.

                    • (): Promise<T>
                    • Returns Promise<T>

                Returns Promise<T>

                Example

                const db = new Database();
                const vertices = db.collection("vertices");
                const edges = db.collection("edges");
                const trx = await db.beginTransaction({ write: [vertices, edges] });

                // The following code will be part of the transaction
                const left = await trx.step(() => vertices.save({ label: "left" }));
                const right = await trx.step(() => vertices.save({ label: "right" }));

                // Results from preceding actions can be used normally
                await trx.step(() => edges.save({
                _from: left._id,
                _to: right._id,
                data: "potato"
                }));

                // Transaction must be committed for changes to take effected
                // Always call either trx.commit or trx.abort to end a transaction
                await trx.commit();

                Example

                // BAD! If the callback is an async function it must only use await once!
                await trx.step(async () => {
                await collection.save(data);
                await collection.save(moreData); // WRONG
                });

                // BAD! Callback function must use only one arangojs call!
                await trx.step(() => {
                return collection.save(data)
                .then(() => collection.save(moreData)); // WRONG
                });

                // BETTER: Wrap every arangojs method call that should be part of the
                // transaction in a separate `trx.step` call
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));

                Example

                // BAD! If the callback is an async function it must not await before
                // calling an arangojs method!
                await trx.step(async () => {
                await doSomethingElse();
                return collection.save(data); // WRONG
                });

                // BAD! Any arangojs inside the callback must not happen inside a promise
                // method!
                await trx.step(() => {
                return doSomethingElse()
                .then(() => collection.save(data)); // WRONG
                });

                // BETTER: Perform any async logic needed outside the `trx.step` call
                await doSomethingElse();
                await trx.step(() => collection.save(data));

                // OKAY: You can perform async logic in the callback after the arangojs
                // method call as long as it does not involve additional arangojs method
                // calls, but this makes it easy to make mistakes later
                await trx.step(async () => {
                await collection.save(data);
                await doSomethingDifferent(); // no arangojs method calls allowed
                });

                Example

                // BAD! The callback should not use any functions that themselves use any
                // arangojs methods!
                async function saveSomeData() {
                await collection.save(data);
                await collection.save(moreData);
                }
                await trx.step(() => saveSomeData()); // WRONG

                // BETTER: Pass the transaction to functions that need to call arangojs
                // methods inside a transaction
                async function saveSomeData(trx) {
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));
                }
                await saveSomeData(); // no `trx.step` call needed

                Example

                // BAD! You must wait for the promise to resolve (or await on the
                // `trx.step` call) before calling `trx.step` again!
                trx.step(() => collection.save(data)); // WRONG
                await trx.step(() => collection.save(moreData));

                // BAD! The trx.step callback can not make multiple calls to async arangojs
                // methods, not even using Promise.all!
                await trx.step(() => Promise.all([ // WRONG
                collection.save(data),
                collection.save(moreData),
                ]));

                // BAD! Multiple `trx.step` calls can not run in parallel!
                await Promise.all([ // WRONG
                trx.step(() => collection.save(data)),
                trx.step(() => collection.save(moreData)),
                ]));

                // BETTER: Always call `trx.step` sequentially, one after the other
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));

                // OKAY: The then callback can be used if async/await is not available
                trx.step(() => collection.save(data))
                .then(() => trx.step(() => collection.save(moreData)));

                Example

                // BAD! The callback will return an empty promise that resolves before
                // the inner arangojs method call has even talked to ArangoDB!
                await trx.step(async () => {
                collection.save(data); // WRONG
                });

                // BETTER: Use an arrow function so you don't forget to return
                await trx.step(() => collection.save(data));

                // OKAY: Remember to always return when using a function body
                await trx.step(() => {
                return collection.save(data); // easy to forget!
                });

                // OKAY: You do not have to use arrow functions but it helps
                await trx.step(function () {
                return collection.save(data);
                });

                Example

                // BAD! You can not pass promises instead of a callback!
                await trx.step(collection.save(data)); // WRONG

                // BETTER: Wrap the code in a function and pass the function instead
                await trx.step(() => collection.save(data));

                Example

                // WORSE: Calls to non-async arangojs methods don't need to be performed
                // as part of a transaction
                const collection = await trx.step(() => db.collection("my-documents"));

                // BETTER: If an arangojs method is not async and doesn't return promises,
                // call it without `trx.step`
                const collection = db.collection("my-documents");

          Returns Promise<T>

    • Optional options: TransactionOptions

      Options for the transaction.

    Returns Promise<T>

    Example

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    await db.withTransaction(
    [
    "vertices",
    edges, // collection instances can be passed directly
    ],
    async (step) => {
    const start = await step(() => vertices.document("a"));
    const end = await step(() => vertices.document("b"));
    await step(() => edges.save({ _from: start._id, _to: end._id }));
    }
    );
  • Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.

    The Collection can be specified as a collection name (string) or an object implementing the collections.ArangoCollection interface: Collection, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.

    Type Parameters

    • T

    Parameters

    • collection: string | ArangoCollection

      A collection that can be read from and written to during the transaction.

    • callback: ((step) => Promise<T>)

      Callback function executing the transaction steps.

        • (step): Promise<T>
        • Parameters

          • step: (<T>(callback) => Promise<T>)
              • <T>(callback): Promise<T>
              • Executes the given function locally as a single step of the transaction.

                Type Parameters

                • T

                  Type of the callback's returned promise.

                Parameters

                • callback: (() => Promise<T>)

                  Callback function returning a promise.

                  Warning: The callback function should wrap a single call of an async arangojs method (e.g. a method on a Collection object of a collection that is involved in the transaction or the db.query method). If the callback function is async, only the first promise-returning (or async) method call will be executed as part of the transaction. See the examples below for how to avoid common mistakes when using this method.

                  Note: Avoid defining the callback as an async function if possible as arangojs will throw an error if the callback did not return a promise. Async functions will return an empty promise by default, making it harder to notice if you forgot to return something from the callback.

                  Note: Although almost anything can be wrapped in a callback and passed to this method, that does not guarantee ArangoDB can actually do it in a transaction. Refer to the ArangoDB documentation if you are unsure whether a given operation can be executed as part of a transaction. Generally any modification or retrieval of data is eligible but modifications of collections or databases are not.

                    • (): Promise<T>
                    • Returns Promise<T>

                Returns Promise<T>

                Example

                const db = new Database();
                const vertices = db.collection("vertices");
                const edges = db.collection("edges");
                const trx = await db.beginTransaction({ write: [vertices, edges] });

                // The following code will be part of the transaction
                const left = await trx.step(() => vertices.save({ label: "left" }));
                const right = await trx.step(() => vertices.save({ label: "right" }));

                // Results from preceding actions can be used normally
                await trx.step(() => edges.save({
                _from: left._id,
                _to: right._id,
                data: "potato"
                }));

                // Transaction must be committed for changes to take effected
                // Always call either trx.commit or trx.abort to end a transaction
                await trx.commit();

                Example

                // BAD! If the callback is an async function it must only use await once!
                await trx.step(async () => {
                await collection.save(data);
                await collection.save(moreData); // WRONG
                });

                // BAD! Callback function must use only one arangojs call!
                await trx.step(() => {
                return collection.save(data)
                .then(() => collection.save(moreData)); // WRONG
                });

                // BETTER: Wrap every arangojs method call that should be part of the
                // transaction in a separate `trx.step` call
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));

                Example

                // BAD! If the callback is an async function it must not await before
                // calling an arangojs method!
                await trx.step(async () => {
                await doSomethingElse();
                return collection.save(data); // WRONG
                });

                // BAD! Any arangojs inside the callback must not happen inside a promise
                // method!
                await trx.step(() => {
                return doSomethingElse()
                .then(() => collection.save(data)); // WRONG
                });

                // BETTER: Perform any async logic needed outside the `trx.step` call
                await doSomethingElse();
                await trx.step(() => collection.save(data));

                // OKAY: You can perform async logic in the callback after the arangojs
                // method call as long as it does not involve additional arangojs method
                // calls, but this makes it easy to make mistakes later
                await trx.step(async () => {
                await collection.save(data);
                await doSomethingDifferent(); // no arangojs method calls allowed
                });

                Example

                // BAD! The callback should not use any functions that themselves use any
                // arangojs methods!
                async function saveSomeData() {
                await collection.save(data);
                await collection.save(moreData);
                }
                await trx.step(() => saveSomeData()); // WRONG

                // BETTER: Pass the transaction to functions that need to call arangojs
                // methods inside a transaction
                async function saveSomeData(trx) {
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));
                }
                await saveSomeData(); // no `trx.step` call needed

                Example

                // BAD! You must wait for the promise to resolve (or await on the
                // `trx.step` call) before calling `trx.step` again!
                trx.step(() => collection.save(data)); // WRONG
                await trx.step(() => collection.save(moreData));

                // BAD! The trx.step callback can not make multiple calls to async arangojs
                // methods, not even using Promise.all!
                await trx.step(() => Promise.all([ // WRONG
                collection.save(data),
                collection.save(moreData),
                ]));

                // BAD! Multiple `trx.step` calls can not run in parallel!
                await Promise.all([ // WRONG
                trx.step(() => collection.save(data)),
                trx.step(() => collection.save(moreData)),
                ]));

                // BETTER: Always call `trx.step` sequentially, one after the other
                await trx.step(() => collection.save(data));
                await trx.step(() => collection.save(moreData));

                // OKAY: The then callback can be used if async/await is not available
                trx.step(() => collection.save(data))
                .then(() => trx.step(() => collection.save(moreData)));

                Example

                // BAD! The callback will return an empty promise that resolves before
                // the inner arangojs method call has even talked to ArangoDB!
                await trx.step(async () => {
                collection.save(data); // WRONG
                });

                // BETTER: Use an arrow function so you don't forget to return
                await trx.step(() => collection.save(data));

                // OKAY: Remember to always return when using a function body
                await trx.step(() => {
                return collection.save(data); // easy to forget!
                });

                // OKAY: You do not have to use arrow functions but it helps
                await trx.step(function () {
                return collection.save(data);
                });

                Example

                // BAD! You can not pass promises instead of a callback!
                await trx.step(collection.save(data)); // WRONG

                // BETTER: Wrap the code in a function and pass the function instead
                await trx.step(() => collection.save(data));

                Example

                // WORSE: Calls to non-async arangojs methods don't need to be performed
                // as part of a transaction
                const collection = await trx.step(() => db.collection("my-documents"));

                // BETTER: If an arangojs method is not async and doesn't return promises,
                // call it without `trx.step`
                const collection = db.collection("my-documents");

          Returns Promise<T>

    • Optional options: TransactionOptions

      Options for the transaction.

    Returns Promise<T>

    Example

    const vertices = db.collection("vertices");
    const start = vertices.document("a");
    const end = vertices.document("b");
    const edges = db.collection("edges");
    await db.withTransaction(
    edges, // collection instances can be passed directly
    async (step) => {
    await step(() => edges.save({ _from: start._id, _to: end._id }));
    }
    );