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

Hierarchy

  • Database

Constructors

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

    See also database.

    Example

    const db = new Database({
    url: "http://127.0.0.1:8529",
    databaseName: "my_database",
    auth: { username: "admin", password: "hunter2" },
    });

    Parameters

    • Optional config: Config

      An object with configuration options.

    Returns Database

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

    See also database.

    Example

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

    Parameters

    • url: string | string[]

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

    • Optional name: string

    Returns Database

Accessors

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

    Returns string

  • get queueTime(): QueueTimeMetrics
  • Methods for accessing the server-reported queue times of the mostly recently received responses.

    Returns QueueTimeMetrics

Methods

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

    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.

    Example

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

    // later
    clearInterval(interval);
    system.close();

    Parameters

    • overwrite: boolean = false

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

    Returns Promise<void>

  • Returns an Analyzer instance representing the Analyzer with the given analyzerName.

    Example

    const db = new Database();
    const analyzer = db.analyzer("some-analyzer");
    const info = await analyzer.get();

    Parameters

    • analyzerName: string

    Returns Analyzer

  • Fetches all Analyzers visible in the database and returns an array of Analyzer instances for those Analyzers.

    See also listAnalyzers.

    Example

    const db = new Database();
    const analyzers = await db.analyzers();
    // analyzers is an array of Analyzer instances

    Returns Promise<Analyzer[]>

  • Begins a new streaming transaction for the given collections, then returns a Transaction instance for the transaction.

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

    Example

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    const trx = await db.beginTransaction({
    read: ["vertices"],
    write: [edges] // collection instances can be passed directly
    });
    const start = await trx.step(() => vertices.document("a"));
    const end = await trx.step(() => vertices.document("b"));
    await trx.step(() => edges.save({ _from: start._id, _to: end._id }));
    await trx.commit();

    Parameters

    Returns Promise<Transaction>

  • Begins a new streaming transaction for the given collections, then returns a Transaction instance for the transaction.

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

    Example

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

    Parameters

    • collections: (string | ArangoCollection)[]

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

    • Optional options: TransactionOptions

      Options for the transaction.

    Returns Promise<Transaction>

  • Begins a new streaming transaction for the given collections, then returns a Transaction instance for the transaction.

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

    Example

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

    Parameters

    Returns Promise<Transaction>

  • Clears the list of recent slow queries.

    See also listSlowQueries.

    Example

    const db = new Database();
    await db.clearSlowQueries();
    // Slow query list is now cleared

    Returns Promise<void>

  • Clears the given ArangoDB user's access level for the database, or the given collection in the given database.

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

    Parameters

    • username: string

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

    • __namedParameters: UserAccessLevelOptions

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

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

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

    Returns void

  • Returns a Collection instance for the given collection name.

    In TypeScript the collection implements both the DocumentCollection and EdgeCollection interfaces and can be cast to either type to enforce a stricter API.

    Example

    const db = new Database();
    const collection = db.collection("potatoes");

    Example

    interface Person {
    name: string;
    }
    const db = new Database();
    const persons = db.collection<Person>("persons");

    Example

    interface Person {
    name: string;
    }
    interface Friend {
    startDate: number;
    endDate?: number;
    }
    const db = new Database();
    const documents = db.collection("persons") as DocumentCollection<Person>;
    const edges = db.collection("friends") as EdgeCollection<Friend>;

    Type Parameters

    • T extends Record<string, any> = any

      Type to use for document data. Defaults to any.

    Parameters

    • collectionName: string

      Name of the edge collection.

    Returns DocumentCollection<T> & EdgeCollection<T>

  • Fetches all collections from the database and returns an array of Collection instances.

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

    See also listCollections.

    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

    Parameters

    • excludeSystem: boolean = true

      Whether system collections should be excluded.

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

  • Writes all locally available services to the database and updates any service bundles missing in the database.

    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

    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>

  • Creates a new Analyzer with the given analyzerName and options, then returns an Analyzer instance for the new Analyzer.

    Example

    const db = new Database();
    const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });
    // the identity Analyzer "potatoes" now exists

    Parameters

    • analyzerName: string

      Name of the Analyzer.

    • options: CreateAnalyzerOptions

      An object defining the properties of the Analyzer.

    Returns Promise<Analyzer>

  • Creates a new collection with the given collectionName and options, then returns a DocumentCollection instance for the new collection.

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

    Type Parameters

    • T extends Record<string, any> = any

      Type to use for document data. Defaults to any.

    Parameters

    Returns Promise<DocumentCollection<T>>

  • Creates a new edge collection with the given collectionName and options, then returns an EdgeCollection instance for the new edge collection.

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

    Type Parameters

    • T extends Record<string, any> = any

      Type to use for edge document data. Defaults to any.

    Parameters

    Returns Promise<EdgeCollection<T>>

  • Creates a new database with the given databaseName with the given options and returns a Database instance for that database.

    Example

    const db = new Database();
    const info = await db.createDatabase("mydb", {
    users: [{ username: "root" }]
    });
    // the database has been created

    Parameters

    • databaseName: string

      Name of the database to create.

    • Optional options: CreateDatabaseOptions

      Options for creating the database.

    Returns Promise<Database>

  • Creates a new database with the given databaseName with the given users and returns a Database instance for that database.

    Example

    const db = new Database();
    const info = await db.createDatabase("mydb", [{ username: "root" }]);
    // the database has been created

    Parameters

    • databaseName: string

      Name of the database to create.

    • users: CreateDatabaseUser[]

      Database users to create with the database.

    Returns Promise<Database>

  • Creates a new edge collection with the given collectionName and options, then returns an EdgeCollection instance for the new edge collection.

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

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

    Type Parameters

    • T extends Record<string, any> = any

      Type to use for edge document data. Defaults to any.

    Parameters

    • collectionName: string

      Name of the new collection.

    • Optional options: CreateCollectionOptions

      Options for creating the collection.

    Returns Promise<EdgeCollection<T>>

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

    Example

    const db = new Database();
    await db.createFunction(
    "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

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

  • Creates a graph with the given graphName and edgeDefinitions, then returns a 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>

  • Creates a new ArangoDB user with the given password.

    Example

    const db = new Database();
    const user = await db.createUser("steve", "hunter2");
    // The user "steve" has been created

    Parameters

    • username: string

      Name of the ArangoDB user to create.

    • passwd: string

      Password of the new ArangoDB user.

    Returns Promise<ArangoApiResponse<ArangoUser>>

  • Creates a new ArangoDB user with the given options.

    Example

    const db = new Database();
    const user = await db.createUser("steve", { passwd: "hunter2" });
    // The user "steve" has been created

    Parameters

    • username: string

      Name of the ArangoDB user to create.

    • options: UserOptions

      Additional options for creating the ArangoDB user.

    Returns Promise<ArangoApiResponse<ArangoUser>>

  • Creates a new View with the given viewName and options, then returns a View instance for the new View.

    Example

    const db = new Database();
    const view = await db.createView("potatoes", { type: "arangosearch" });
    // the ArangoSearch View "potatoes" now exists

    Parameters

    • viewName: string

      Name of the View.

    • options: CreateViewOptions

      An object defining the properties of the View.

    Returns Promise<View>

  • Creates a new Database instance for the given databaseName that shares this database's connection pool.

    See also new Database.

    Example

    const systemDb = new Database();
    const myDb = system.database("my_database");

    Parameters

    • databaseName: string

      Name of the database.

    Returns Database

  • Fetches all databases from the server and returns an array of Database instances for those databases.

    See also listDatabases and userDatabases.

    Example

    const db = new Database();
    const names = await db.databases();
    // databases is an array of databases

    Returns Promise<Database[]>

  • Retrieves a zip bundle containing the service files.

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

    Example

    const db = new Database();
    const serviceBundle = await db.downloadService("/my-foxx");

    Parameters

    • mount: string

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

    Returns Promise<Blob | Buffer>

  • Deletes the database with the given databaseName from the server.

    Example

    const db = new Database();
    await db.dropDatabase("mydb");
    // database "mydb" no longer exists

    Parameters

    • databaseName: string

      Name of the database to delete.

    Returns Promise<boolean>

  • Deletes the AQL user function with the given name from the database.

    Example

    const db = new Database();
    await db.dropFunction("ACME::ACCOUNTING::CALCULATE_VAT");
    // the function no longer exists

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

  • Performs a server-side JavaScript transaction and returns its return value.

    Collections can be specified as collection names (strings) or objects implementing the ArangoCollection interface: Collection, GraphVertexCollection, GraphEdgeCollection as well as (in TypeScript) DocumentCollection and 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.

    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

    Parameters

    • collections: TransactionCollections & {
          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>

  • Performs a server-side transaction and returns its return value.

    Collections can be specified as collection names (strings) or objects implementing the ArangoCollection interface: Collection, GraphVertexCollection, GraphEdgeCollection as well as (in TypeScript) DocumentCollection and 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.

    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

    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>

  • 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 ArangoCollection interface: Collection, GraphVertexCollection, GraphEdgeCollection as well as (in TypeScript) DocumentCollection and 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.

    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

    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>

  • Checks whether the database exists.

    Example

    const db = new Database();
    const result = await db.exists();
    // result indicates whether the database exists

    Returns Promise<boolean>

  • Explains a database query using the given query.

    See the 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.

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

    Parameters

    • query: AqlQuery

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

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

      Options for explaining the query.

    Returns Promise<ArangoApiResponse<SingleExplainResult>>

  • Explains a database query using the given query.

    See the 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.

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

    Parameters

    • query: AqlQuery

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

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

      Options for explaining the query.

    Returns Promise<ArangoApiResponse<MultiExplainResult>>

  • Explains a database query using the given query and bindVars.

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

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

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

  • Explains a database query using the given query and bindVars.

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

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

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

  • Fetches the database description for the active database from the server.

    Example

    const db = new Database();
    const info = await db.get();
    // the database exists

    Returns Promise<DatabaseInfo>

  • Retrieves information about a mounted service.

    Example

    const db = new Database();
    const info = await db.getService("/my-service");
    // info contains detailed information about the service

    Parameters

    • mount: string

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

    Returns Promise<ServiceInfo>

  • Retrieves information about the service's configuration options and their current values.

    See also replaceServiceConfiguration and updateServiceConfiguration.

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

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

  • Retrieves information about the service's configuration options and their current values.

    See also replaceServiceConfiguration and updateServiceConfiguration.

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

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

  • Retrieves information about the service's dependencies and their current mount points.

    See also replaceServiceDependencies and updateServiceDependencies.

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

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

  • Retrieves information about the service's dependencies and their current mount points.

    See also replaceServiceDependencies and updateServiceDependencies.

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

    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[]>>

  • Retrieves an Open API compatible Swagger API description object for the service installed at the given mount point.

    Example

    const db = new Database();
    const spec = await db.getServiceDocumentation("/my-service");
    // spec is a Swagger API description of the service

    Parameters

    • mount: string

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

    Returns Promise<SwaggerJson>

  • Retrieves the text content of the service's README or README.md file.

    Returns undefined if no such file could be found.

    Example

    const db = new Database();
    const readme = await db.getServiceReadme("/my-service");
    if (readme !== undefined) console.log(readme);
    else console.warn(`No README found.`)

    Parameters

    • mount: string

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

    Returns Promise<undefined | string>

  • Fetches the user data of a single ArangoDB user.

    Example

    const db = new Database();
    const user = await db.getUser("steve");
    // user is the user object for the user named "steve"

    Parameters

    • username: string

      Name of the ArangoDB user to fetch.

    Returns Promise<ArangoApiResponse<ArangoUser>>

  • Fetches the given ArangoDB user's access level for the database, or the given collection in the given database.

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

    Parameters

    • username: string

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

    • __namedParameters: UserAccessLevelOptions

    Returns Promise<AccessLevel>

  • Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases.

    Example

    const db = new Database();
    const accessLevels = await db.getUserDatabases("steve");
    for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {
    console.log(`${databaseName}: ${accessLevel}`);
    }

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

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

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

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

  • Returns a Graph instance representing the graph with the given graphName.

    Example

    const db = new Database();
    const graph = db.graph("some-graph");

    Parameters

    • graphName: string

      Name of the graph.

    Returns Graph

  • Fetches all graphs from the database and returns an array of Graph instances for those graphs.

    See also listGraphs.

    Example

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

    Returns Promise<Graph[]>

  • Installs a new service.

    Example

    const db = new Database();
    // Using a node.js file stream as source
    const source = fs.createReadStream("./my-foxx-service.zip");
    const info = await db.installService("/hello", source);

    Example

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

    Example

    const db = new Database();
    // Using a File (Blob) from a browser file input
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.installService("/hello", source);

    Parameters

    • mount: string

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

    • source: string | Readable | Blob | Buffer

      The service bundle to install.

    • options: InstallServiceOptions = {}

      Options for installing the service.

    Returns Promise<ServiceInfo>

  • Kills a running query with the given queryId.

    See also listRunningQueries.

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

    Parameters

    • queryId: string

      The ID of a currently running query.

    Returns Promise<void>

  • Fetches all Analyzers visible in the database and returns an array of Analyzer descriptions.

    See also analyzers.

    Example

    const db = new Database();
    const analyzers = await db.listAnalyzers();
    // analyzers is an array of Analyzer descriptions

    Returns Promise<AnalyzerDescription[]>

  • Fetches all collections from the database and returns an array of collection descriptions.

    See also collections.

    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

    Parameters

    • excludeSystem: boolean = true

      Whether system collections should be excluded.

    Returns Promise<CollectionMetadata[]>

  • Fetches all databases from the server and returns an array of their names.

    See also databases and listUserDatabases.

    Example

    const db = new Database();
    const names = await db.listDatabases();
    // databases is an array of database names

    Returns Promise<string[]>

  • Fetches a list of all AQL user functions registered with the database.

    Example

    const db = new Database();
    const functions = await db.listFunctions();
    const names = functions.map(fn => fn.name);

    Returns Promise<AqlUserFunction[]>

  • Fetches all graphs from the database and returns an array of graph descriptions.

    See also graphs.

    Example

    const db = new Database();
    const graphs = await db.listGraphs();
    // graphs is an array of graph descriptions

    Returns Promise<GraphInfo[]>

  • Fetches a list of information for all currently running queries.

    See also listSlowQueries and killQuery.

    Example

    const db = new Database();
    const queries = await db.listRunningQueries();

    Returns Promise<QueryInfo[]>

  • Retrieves a list of scripts defined in the service manifest's "scripts" section mapped to their human readable representations.

    Example

    const db = new Database();
    const scripts = await db.listServiceScripts("/my-service");
    for (const [name, title] of Object.entries(scripts)) {
    console.log(`${name}: ${title}`);
    }

    Parameters

    • mount: string

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

    Returns Promise<Record<string, string>>

  • Fetches a list of all installed service.

    Example

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

    Example

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

    Parameters

    • excludeSystem: boolean = true

      Whether system services should be excluded.

    Returns Promise<ServiceSummary[]>

  • Fetches a list of information for all recent slow queries.

    See also listRunningQueries and clearSlowQueries.

    Example

    const db = new Database();
    const queries = await db.listSlowQueries();
    // Only works if slow query tracking is enabled

    Returns Promise<QueryInfo[]>

  • Fetches all active transactions from the database and returns an array of transaction descriptions.

    See also transactions.

    Example

    const db = new Database();
    const transactions = await db.listTransactions();
    // transactions is an array of transaction descriptions

    Returns Promise<TransactionDetails[]>

  • Fetches all databases accessible to the active user from the server and returns an array of their names.

    See also userDatabases and listDatabases.

    Example

    const db = new Database();
    const names = await db.listUserDatabases();
    // databases is an array of database names

    Returns Promise<string[]>

  • Fetches all ArangoDB users visible to the authenticated user and returns an array of user objects.

    Example

    const db = new Database();
    const users = await db.listUsers();
    // users is an array of user objects

    Returns Promise<ArangoUser[]>

  • Fetches all Views from the database and returns an array of View descriptions.

    See also views.

    Example

    const db = new Database();

    const views = await db.listViews();
    // views is an array of View descriptions

    Returns Promise<ViewDescription[]>

  • Validates the given database credentials and exchanges them for an authentication token, then uses the authentication token for future requests and returns it.

    Example

    const db = new Database();
    await db.login("admin", "hunter2");
    // with an authentication token for the "admin" user.

    Parameters

    • username: string = "root"

      The username to authenticate with.

    • password: string = ""

      The password to authenticate with.

    Returns Promise<string>

  • Parses the given query and returns the result.

    See the 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.

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

    Parameters

    • query: string | AqlLiteral | AqlQuery

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

    Returns Promise<ParseResult>

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

    See the 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.

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

    Type Parameters

    • T = any

    Parameters

    • query: AqlQuery

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

    • Optional options: QueryOptions

      Options for the query execution.

    Returns Promise<ArrayCursor<T>>

  • Performs a database query using the given query and bindVars, then returns a new ArrayCursor instance for the result set.

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

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

    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<ArrayCursor<T>>

  • Fetches the available optimizer rules.

    Example

    const db = new Database();
    const rules = await db.queryRules();
    for (const rule of rules) {
    console.log(rule.name);
    }

    Returns Promise<QueryOptimizerRule[]>

  • Fetches the query tracking properties.

    Example

    const db = new Database();
    const tracking = await db.queryTracking();
    console.log(tracking.enabled);

    Returns Promise<QueryTracking>

  • Modifies the query tracking properties.

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

    Parameters

    Returns Promise<QueryTracking>

  • Removes the ArangoDB user with the given username from the server.

    Example

    const db = new Database();
    await db.removeUser("steve");
    // The user "steve" has been removed

    Parameters

    • username: string

      Name of the ArangoDB user to remove.

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

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

  • Renames the view viewName to newName.

    Additionally removes any stored 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 useBearerAuth or returned and used by login. If a new authentication token is issued, it will be used for future requests and returned.

    Example

    const db = new Database();
    await db.login("admin", "hunter2");
    // ... later ...
    const newToken = await db.renewAuthToken();
    if (!newToken) // no new token issued

    Returns Promise<null | string>

  • Replaces an existing service with a new service by completely removing the old service and installing a new service at the same mount point.

    Example

    const db = new Database();
    // Using a node.js file stream as source
    const source = fs.createReadStream("./my-foxx-service.zip");
    const info = await db.replaceService("/hello", source);

    Example

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

    Example

    const db = new Database();
    // Using a File (Blob) from a browser file input
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.replaceService("/hello", source);

    Parameters

    • mount: string

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

    • source: string | Readable | Blob | Buffer

      The service bundle to install.

    • options: ReplaceServiceOptions = {}

      Options for replacing the service.

    Returns Promise<ServiceInfo>

  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also updateServiceConfiguration and getServiceConfiguration.

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

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

  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also updateServiceConfiguration and getServiceConfiguration.

    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]}`);
    }

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

  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also updateServiceDependencies and getServiceDependencies.

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

    Parameters

    • mount: string

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

    • deps: Record<string, string>
    • 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, Object>>

  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also updateServiceDependencies and getServiceDependencies.

    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]}`);
    }

    Parameters

    • mount: string

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

    • deps: Record<string, string>
    • 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>;
    }>

  • Replaces the ArangoDB user's option with the new options.

    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

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

  • Returns a new Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.

    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"}'

    Parameters

    • Optional path: string

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

    • Optional headers: Headers

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

    Returns Route

  • Executes a service script and retrieves its result exposed as module.exports (if any).

    Example

    const db = new Database();
    const result = await db.runServiceScript(
    "/my-service",
    "create-user",
    {
    username: "service_admin",
    password: "hunter2"
    }
    );

    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>

  • Runs the tests of a given service and returns the results using the "default" reporter.

    Example

    const db = new Database();
    const testReport = await db.runServiceTests("/my-foxx");

    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>

  • Runs the tests of a given service and returns the results using the "suite" reporter, which groups the test result by test suite.

    Example

    const db = new Database();
    const suiteReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "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>

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

    Example

    const db = new Database();
    const streamEvents = await db.runServiceTests(
    "/my-foxx",
    { reporter: "stream" }
    );

    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>

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

    Example

    const db = new Database();
    const tapLines = await db.runServiceTests(
    "/my-foxx",
    { reporter: "tap" }
    );

    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>

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

    Example

    const db = new Database();
    const jsonML = await db.runServiceTests(
    "/my-foxx",
    { reporter: "xunit" }
    );

    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>

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

    Example

    const db = new Database();
    const streamReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "stream", idiomatic: true }
    );

    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>

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

    Example

    const db = new Database();
    const tapReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "tap", idiomatic: true }
    );

    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>

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

    Example

    const db = new Database();
    const xml = await db.runServiceTests(
    "/my-foxx",
    { reporter: "xunit", idiomatic: true }
    );

    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>

  • Sets the limit for the number of values of the most recently received server-reported queue times that can be accessed using queueTime.

    Parameters

    • responseQueueTimeSamples: number

      Number of values to maintain.

    Returns void

  • Enables or disables development mode for the given service.

    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

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

  • Sets the given ArangoDB user's access level for the database, or the given collection in the given database.

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

    Parameters

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

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

    See also beginTransaction.

    Example

    const trx1 = await db.beginTransaction(collections);
    const id = trx1.id;
    // later
    const trx2 = db.transaction(id);
    await trx2.commit();

    Parameters

    • transactionId: string

    Returns Transaction

  • Fetches all active transactions from the database and returns an array of Transaction instances for those transactions.

    See also listTransactions.

    Example

    const db = new Database();
    const transactions = await db.transactions();
    // transactions is an array of transactions

    Returns Promise<Transaction[]>

  • Completely removes a service from the database.

    Example

    const db = new Database();
    await db.uninstallService("/my-foxx");

    Parameters

    • mount: string

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

    • Optional options: UninstallServiceOptions

      Options for uninstalling the service.

    Returns Promise<void>

  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also replaceServiceConfiguration and getServiceConfiguration.

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

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

  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also replaceServiceConfiguration and getServiceConfiguration.

    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]}`);
    }

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

  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also replaceServiceDependencies and getServiceDependencies.

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

    Parameters

    • mount: string

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

    • deps: Record<string, string>
    • 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, Object>>

  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also replaceServiceDependencies and getServiceDependencies.

    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]}`);
    }

    Parameters

    • mount: string

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

    • deps: Record<string, string>
    • 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>;
    }>

  • Sets the password of a given ArangoDB user to the new value.

    Example

    const db = new Database();
    const user = await db.updateUser("steve", "hunter2");
    // The user "steve" has received a new password

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

  • Updates the ArangoDB user with the new options.

    Example

    const db = new Database();
    const user = await db.updateUser("steve", { active: false });
    // The user "steve" has been set to inactive

    Parameters

    • username: string

      Name of the ArangoDB user to modify.

    • options: Partial<UserOptions>

      Options of the ArangoDB user to modify.

    Returns Promise<ArangoApiResponse<ArangoUser>>

  • Replaces an existing service with a new service while retaining the old service's configuration and dependencies.

    Example

    const db = new Database();
    // Using a node.js file stream as source
    const source = fs.createReadStream("./my-foxx-service.zip");
    const info = await db.upgradeService("/hello", source);

    Example

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

    Example

    const db = new Database();
    // Using a File (Blob) from a browser file input
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.upgradeService("/hello", source);

    Parameters

    • mount: string

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

    • source: string | Readable | Blob | Buffer

      The service bundle to install.

    • options: UpgradeServiceOptions = {}

      Options for upgrading the service.

    Returns Promise<ServiceInfo>

  • Updates the underlying connection's authorization header to use Basic authentication with the given username and password, then returns itself.

    Example

    const db = new Database();
    db.useBasicAuth("admin", "hunter2");
    // with the username "admin" and password "hunter2".

    Parameters

    • username: string = "root"

      The username to authenticate with.

    • password: string = ""

      The password to authenticate with.

    Returns Database

  • Updates the underlying connection's authorization header to use Bearer authentication with the given authentication token, then returns itself.

    Example

    const db = new Database();
    db.useBearerAuth("keyboardcat");
    // The database instance now uses Bearer authentication.

    Parameters

    • token: string

      The token to authenticate with.

    Returns Database

  • Fetches all databases accessible to the active user from the server and returns an array of Database instances for those databases.

    See also listUserDatabases and databases.

    Example

    const db = new Database();
    const names = await db.userDatabases();
    // databases is an array of databases

    Returns Promise<Database[]>

  • Fetches version information from the ArangoDB server.

    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

    Parameters

    • Optional details: boolean

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

    Returns Promise<VersionInfo>

  • Returns a View instance for the given viewName.

    Example

    const db = new Database();
    const view = db.view("potatoes");

    Parameters

    • viewName: string

      Name of the ArangoSearch or SearchAlias View.

    Returns View

  • Fetches all Views from the database and returns an array of View instances for the Views.

    See also listViews.

    Example

    const db = new Database();
    const views = await db.views();
    // views is an array of ArangoSearch View instances

    Returns Promise<View[]>

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

    Example

    const db = new Database({ loadBalancingStrategy: "ROUND_ROBIN" });
    await system.acquireHostList();
    const analyzer = db.analyzer("my-analyzer");
    await analyzer.create();
    await db.waitForPropagation(
    { path: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },
    30000
    );
    // Analyzer has been propagated to all coordinators and can safely be used

    Parameters

    • request: RequestOptions

      Request to perform against each known coordinator.

    • Optional timeout: number

      Maximum number of milliseconds to wait for propagation.

    Returns Promise<void>

Generated using TypeDoc