Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Database

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

Hierarchy

  • Database

Index

Constructors

constructor

  • new Database(config?: Config): Database
  • new Database(url: string | string[], name?: undefined | string): Database
  • Creates a new Database instance with its own connection pool.

    See also Database.database.

    example
    const db = new Database({
      url: "http://localhost: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.database.

    example
    const db = new Database("http://localhost: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: undefined | string

    Returns Database

Accessors

isArangoDatabase

  • get isArangoDatabase(): true
  • internal

    Indicates that this object represents an ArangoDB database.

    Returns true

name

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

    Returns string

Methods

acquireHostList

  • acquireHostList(): Promise<void>
  • 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);
    db.close();

    Returns Promise<void>

analyzer

  • analyzer(analyzerName: string): Analyzer
  • 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

analyzers

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

    See also Database.listAnalyzers.

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

    Returns Promise<Analyzer[]>

beginTransaction

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

clearSlowQueries

  • clearSlowQueries(): Promise<void>
  • Clears the list of recent slow queries.

    See also Database.listSlowQueries.

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

    Returns Promise<void>

close

  • close(): void
  • 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
      db.close();
    }, 1000 * 60 * 60);

    Returns void

collection

  • 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: object

      Type to use for document data. Defaults to any.

    Parameters

    • collectionName: string

      Name of the edge collection.

    Returns DocumentCollection<T> & EdgeCollection<T>

collections

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

    • Default value excludeSystem: boolean = true

      Whether system collections should be excluded.

    Returns Promise<Array<DocumentCollection & EdgeCollection>>

commitLocalServiceState

  • commitLocalServiceState(replace?: boolean): Promise<void>
  • 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

    • Default value 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>

createAnalyzer

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

createCollection

  • 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: object

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

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

    Parameters

    Returns Promise<EdgeCollection<T>>

createDatabase

  • 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
    db.useDatabase("mydb");
    db.useBasicAuth("root", "");

    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
    db.useDatabase("mydb");
    db.useBasicAuth("root", "");

    Parameters

    • databaseName: string

      Name of the database to create.

    • users: CreateDatabaseUser[]

      Database users to create with the database.

    Returns Promise<Database>

createEdgeCollection

  • 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 Database.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: object

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

createFunction

  • createFunction(name: string, code: string, isDeterministic?: boolean): Promise<ArangoResponseMetadata & { isNewlyCreated: boolean }>
  • 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).

    • Default value 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<ArangoResponseMetadata & { isNewlyCreated: boolean }>

createGraph

  • 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: GraphCreateOptions

      An object defining the properties of the graph.

    Returns Promise<Graph>

createView

  • Creates a new ArangoSearch View with the given viewName and options and returns an ArangoSearchView instance for the created View.

    example
    const db = new Database();
    const view = await db.createView("potatoes");
    // the ArangoSearch View "potatoes" now exists

    Parameters

    Returns Promise<ArangoSearchView>

database

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

    See also Database.constructor.

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

    Parameters

    • databaseName: string

      Name of the database.

    Returns Database

databases

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

    See also Database.listDatabases and Database.userDatabases.

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

    Returns Promise<Database[]>

downloadService

  • downloadService(mount: string): Promise<Buffer | Blob>
  • 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<Buffer | Blob>

dropDatabase

  • dropDatabase(databaseName: string): Promise<boolean>
  • 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>

dropFunction

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

    • Default value 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<ArangoResponseMetadata & { deletedCount: number }>

executeTransaction

  • 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?: undefined | false | true }

      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>

exists

  • exists(): Promise<boolean>
  • Checks whether the database exists.

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

    Returns Promise<boolean>

explain

  • 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?: undefined | false }

      Options for explaining the query.

    Returns Promise<ArangoResponseMetadata & 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<ArangoResponseMetadata & 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: Dict<any>

      An object defining bind parameters for the query.

    • Optional options: ExplainOptions & { allPlans?: undefined | false }

      Options for explaining the query.

    Returns Promise<ArangoResponseMetadata & 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: Dict<any>

      An object defining bind parameters for the query.

    • Optional options: ExplainOptions & { allPlans: true }

      Options for explaining the query.

    Returns Promise<ArangoResponseMetadata & MultiExplainResult>

get

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

getService

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

getServiceConfiguration

  • getServiceConfiguration(mount: string, minimal?: undefined | false): Promise<Dict<ServiceConfiguration>>
  • getServiceConfiguration(mount: string, minimal: true): Promise<Dict<any>>
  • Retrieves information about the service's configuration options and their current values.

    See also Database.replaceServiceConfiguration and Database.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: undefined | 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<Dict<ServiceConfiguration>>

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

    See also Database.replaceServiceConfiguration and Database.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<Dict<any>>

getServiceDependencies

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

    See also Database.replaceServiceDependencies and Database.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: undefined | 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<Dict<SingleServiceDependency | MultiServiceDependency>>

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

    See also Database.replaceServiceDependencies and Database.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<Dict<string | string[] | undefined>>

getServiceDocumentation

  • getServiceDocumentation(mount: string): Promise<SwaggerJson>
  • 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>

getServiceReadme

  • getServiceReadme(mount: string): Promise<string | undefined>
  • 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<string | undefined>

graph

  • graph(graphName: string): Graph
  • 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

graphs

  • graphs(): Promise<Graph[]>
  • Fetches all graphs from the database and returns an array of Graph instances for those graphs.

    See also Database.listGraphs.

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

    Returns Promise<Graph[]>

installService

  • 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: Readable | Buffer | Blob | string

      The service bundle to install.

    • Default value options: InstallServiceOptions = {}

      Options for installing the service.

    Returns Promise<ServiceInfo>

killQuery

  • killQuery(queryId: string): Promise<void>
  • Kills a running query with the given queryId.

    See also Database.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>

listAnalyzers

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

    See also Database.analyzers.

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

    Returns Promise<AnalyzerDescription[]>

listCollections

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

    See also Database.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

    • Default value excludeSystem: boolean = true

      Whether system collections should be excluded.

    Returns Promise<CollectionMetadata[]>

listDatabases

  • listDatabases(): Promise<string[]>
  • Fetches all databases from the server and returns an array of their names.

    See also Database.databases and Database.listUserDatabases.

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

    Returns Promise<string[]>

listFunctions

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

listGraphs

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

    See also Database.graphs.

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

    Returns Promise<GraphInfo[]>

listRunningQueries

listServiceScripts

  • listServiceScripts(mount: string): Promise<Dict<string>>
  • 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<Dict<string>>

listServices

  • 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

    • Default value excludeSystem: boolean = true

      Whether system services should be excluded.

    Returns Promise<ServiceSummary[]>

listSlowQueries

listTransactions

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

    See also Database.transactions.

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

    Returns Promise<TransactionDetails[]>

listUserDatabases

  • listUserDatabases(): Promise<string[]>
  • 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.

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

    Returns Promise<string[]>

listViews

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

    See also Database.views.

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

    Returns Promise<ViewDescription[]>

login

  • login(username?: string, password?: string): Promise<string>
  • 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();
    db.useDatabase("test");
    await db.login("admin", "hunter2");
    // The database instance now uses the database "test"
    // with an authentication token for the "admin" user.

    Parameters

    • Default value username: string = "root"

      The username to authenticate with.

    • Default value password: string = ""

      The password to authenticate with.

    Returns Promise<string>

parse

  • 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 | AqlQuery | AqlLiteral

      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>

query

  • 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;
    
    // Using an aql template string
    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;
    
    // 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 }
    });

    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>

  • 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 cursor = await db.query(
      // A normal multi-line string
      `
        FOR u IN _users
        FILTER u.authData.active == @active
        RETURN u.user
      `,
      { active: active }
    );
    example
    const db = new Database();
    const active = true;
    
    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 }
    );

    Parameters

    • query: string | AqlLiteral

      An AQL query string.

    • Optional bindVars: Dict<any>

      An object defining bind parameters for the query.

    • Optional options: QueryOptions

      Options for the query execution.

    Returns Promise<ArrayCursor>

queryTracking

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

renameCollection

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

renameView

  • 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<ArangoResponseMetadata & ViewDescription>

replaceService

  • 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: Readable | Buffer | Blob | string

      The service bundle to install.

    • Default value options: ReplaceServiceOptions = {}

      Options for replacing the service.

    Returns Promise<ServiceInfo>

replaceServiceConfiguration

  • replaceServiceConfiguration(mount: string, cfg: Dict<any>, minimal?: undefined | false): Promise<Dict<ServiceConfiguration & { warning?: undefined | string }>>
  • replaceServiceConfiguration(mount: string, cfg: Dict<any>, minimal: true): Promise<{ values: Dict<any>; warnings: Dict<string | undefined> }>
  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also Database.updateServiceConfiguration and Database.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: Dict<any>

      An object mapping configuration option names to values.

    • Optional minimal: undefined | 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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full configuration definitions.

    Returns Promise<Dict<ServiceConfiguration & { warning?: undefined | string }>>

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

    See also Database.updateServiceConfiguration and Database.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: Dict<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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full configuration definitions.

    Returns Promise<{ values: Dict<any>; warnings: Dict<string | undefined> }>

replaceServiceDependencies

  • replaceServiceDependencies(mount: string, deps: Dict<string>, minimal?: undefined | false): Promise<Dict<{ current?: undefined | string; description?: undefined | string; multiple: false; name: string; required: boolean; title: string; version: string } | { current?: string[]; description?: undefined | string; multiple: true; name: string; required: boolean; title: string; version: string } & { warning?: undefined | string }>>
  • replaceServiceDependencies(mount: string, deps: Dict<string>, minimal: true): Promise<{ values: Dict<string>; warnings: Dict<string | undefined> }>
  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also Database.updateServiceDependencies and Database.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: Dict<string>
    • Optional minimal: undefined | 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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full dependency definitions.

    Returns Promise<Dict<{ current?: undefined | string; description?: undefined | string; multiple: false; name: string; required: boolean; title: string; version: string } | { current?: string[]; description?: undefined | string; multiple: true; name: string; required: boolean; title: string; version: string } & { warning?: undefined | string }>>

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

    See also Database.updateServiceDependencies and Database.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: Dict<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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full dependency definitions.

    Returns Promise<{ values: Dict<string>; warnings: Dict<string | undefined> }>

request

  • request<T>(options: RequestOptions & { absolutePath?: undefined | false | true }, transform?: undefined | ((res: ArangojsResponse) => T)): Promise<T>
  • internal

    Performs an arbitrary HTTP request against the database.

    If absolutePath is set to true, the database path will not be automatically prepended to the basePath.

    Type parameters

    • T

      Return type to use. Defaults to the response object type.

    Parameters

    • options: RequestOptions & { absolutePath?: undefined | false | true }

      Options for this request.

    • Optional transform: undefined | ((res: ArangojsResponse) => T)

      An optional function to transform the low-level response object to a more useful return value.

    Returns Promise<T>

route

  • route(path?: undefined | string, headers?: Headers): Route
  • 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: undefined | 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

runServiceScript

  • runServiceScript(mount: string, name: string, params?: any): Promise<any>
  • 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>

runServiceTests

  • runServiceTests(mount: string, options?: undefined | { filter?: undefined | string; idiomatic?: undefined | false; reporter?: undefined | "default" }): Promise<ServiceTestDefaultReport>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic?: undefined | false; reporter: "suite" }): Promise<ServiceTestSuiteReport>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic?: undefined | false; reporter: "stream" }): Promise<ServiceTestStreamReport>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic?: undefined | false; reporter: "tap" }): Promise<ServiceTestTapReport>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic?: undefined | false; reporter: "xunit" }): Promise<ServiceTestXunitReport>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic: true; reporter: "stream" }): Promise<string>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic: true; reporter: "tap" }): Promise<string>
  • runServiceTests(mount: string, options: { filter?: undefined | string; idiomatic: true; reporter: "xunit" }): Promise<string>
  • 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: undefined | { filter?: undefined | string; idiomatic?: undefined | false; reporter?: undefined | "default" }

      Options for running the tests.

    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?: undefined | string; idiomatic?: undefined | false; reporter: "suite" }

      Options for running the tests.

      • Optional filter?: undefined | string

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

      • Optional idiomatic?: undefined | 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?: undefined | string; idiomatic?: undefined | false; reporter: "stream" }

      Options for running the tests.

      • Optional filter?: undefined | string

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

      • Optional idiomatic?: undefined | 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?: undefined | string; idiomatic?: undefined | false; reporter: "tap" }

      Options for running the tests.

      • Optional filter?: undefined | string

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

      • Optional idiomatic?: undefined | 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?: undefined | string; idiomatic?: undefined | false; reporter: "xunit" }

      Options for running the tests.

      • Optional filter?: undefined | string

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

      • Optional idiomatic?: undefined | 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?: undefined | string; idiomatic: true; reporter: "stream" }

      Options for running the tests.

      • Optional filter?: undefined | 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?: undefined | string; idiomatic: true; reporter: "tap" }

      Options for running the tests.

      • Optional filter?: undefined | 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?: undefined | string; idiomatic: true; reporter: "xunit" }

      Options for running the tests.

      • Optional filter?: undefined | 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>

setServiceDevelopmentMode

  • setServiceDevelopmentMode(mount: string, enabled?: boolean): Promise<ServiceInfo>
  • 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.

    • Default value enabled: boolean = true

      Whether development mode should be enabled or disabled.

    Returns Promise<ServiceInfo>

transaction

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

    See also Database.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

transactions

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

    See also Database.listTransactions.

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

    Returns Promise<Transaction[]>

uninstallService

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

updateServiceConfiguration

  • updateServiceConfiguration(mount: string, cfg: Dict<any>, minimal?: undefined | false): Promise<Dict<ServiceConfiguration & { warning?: undefined | string }>>
  • updateServiceConfiguration(mount: string, cfg: Dict<any>, minimal: true): Promise<{ values: Dict<any>; warnings: Dict<string | undefined> }>
  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also Database.replaceServiceConfiguration and Database.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: Dict<any>

      An object mapping configuration option names to values.

    • Optional minimal: undefined | 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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full configuration definitions.

    Returns Promise<Dict<ServiceConfiguration & { warning?: undefined | string }>>

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

    See also Database.replaceServiceConfiguration and Database.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: Dict<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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full configuration definitions.

    Returns Promise<{ values: Dict<any>; warnings: Dict<string | undefined> }>

updateServiceDependencies

  • updateServiceDependencies(mount: string, deps: Dict<string>, minimal?: undefined | false): Promise<Dict<{ current?: undefined | string; description?: undefined | string; multiple: false; name: string; required: boolean; title: string; version: string } | { current?: string[]; description?: undefined | string; multiple: true; name: string; required: boolean; title: string; version: string } & { warning?: undefined | string }>>
  • updateServiceDependencies(mount: string, deps: Dict<string>, minimal: true): Promise<{ values: Dict<string>; warnings: Dict<string | undefined> }>
  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also Database.replaceServiceDependencies and Database.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: Dict<string>
    • Optional minimal: undefined | 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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full dependency definitions.

    Returns Promise<Dict<{ current?: undefined | string; description?: undefined | string; multiple: false; name: string; required: boolean; title: string; version: string } | { current?: string[]; description?: undefined | string; multiple: true; name: string; required: boolean; title: string; version: string } & { warning?: undefined | string }>>

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

    See also Database.replaceServiceDependencies and Database.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: Dict<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.

      Note: When using ArangoDB 3.2.8 or older, setting the minimal option to true avoids triggering a second request to fetch the full dependency definitions.

    Returns Promise<{ values: Dict<string>; warnings: Dict<string | undefined> }>

upgradeService

  • 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: Readable | Buffer | Blob | string

      The service bundle to install.

    • Default value options: UpgradeServiceOptions = {}

      Options for upgrading the service.

    Returns Promise<ServiceInfo>

useBasicAuth

  • useBasicAuth(username?: string, password?: string): this
  • Updates the Database instance's authorization header to use Basic authentication with the given username and password, then returns itself.

    example
    const db = new Database();
    db.useDatabase("test");
    db.useBasicAuth("admin", "hunter2");
    // The database instance now uses the database "test"
    // with the username "admin" and password "hunter2".

    Parameters

    • Default value username: string = "root"

      The username to authenticate with.

    • Default value password: string = ""

      The password to authenticate with.

    Returns this

useBearerAuth

  • useBearerAuth(token: string): this
  • Updates the Database instance'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 this

useDatabase

  • useDatabase(databaseName: string): this
  • Updates the Database instance and its connection string to use the given databaseName, then returns itself.

    Note: This also affects all collections, cursors and other arangojs objects originating from this database object, which may cause unexpected results.

    deprecated

    Use Database.database instead.

    example
    const systemDb = new Database();
    // systemDb.useDatabase("my_database"); // deprecated
    const myDb = systemDb.database("my_database");

    Parameters

    • databaseName: string

      Name of the database to use.

    Returns this

userDatabases

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

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

    Returns Promise<Database[]>

version

  • version(details?: undefined | false | true): Promise<VersionInfo>
  • 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: undefined | false | true

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

    Returns Promise<VersionInfo>

view

  • Returns an ArangoSearchView instance for the given viewName.

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

    Parameters

    • viewName: string

      Name of the ArangoSearch View.

    Returns ArangoSearchView

views

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

    See also Database.listViews.

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

    Returns Promise<ArangoSearchView[]>

Generated using TypeDoc