arangojs
- Version 10.1.1
- Published
- 3.95 MB
- 1 dependency
- Apache-2.0 license
Install
npm i arangojs
yarn add arangojs
pnpm add arangojs
Overview
import arangojs, { aql, Database } from "arangojs";
The "index" module is the default entry point when importing the arangojs module or using the web build in the browser.
If you are just getting started, you probably want to use the arangojs function, which is also the default export of this module, or the databases.Database class for which it is a wrapper.
Index
Functions
Classes
Database
- acquireHostList()
- analyzer()
- analyzers()
- availability()
- beginTransaction()
- clearQueryCache()
- clearSlowQueries()
- clearUserAccessLevel()
- close()
- collection()
- collections()
- commitLocalServiceState()
- compact()
- computeClusterRebalance()
- createAnalyzer()
- createCollection()
- createDatabase()
- createEdgeCollection()
- createGraph()
- createHotBackup()
- createJob()
- createUser()
- createUserFunction()
- createView()
- database()
- databases()
- deleteAllJobResults()
- deleteExpiredJobResults()
- deleteHotBackup()
- downloadService()
- dropDatabase()
- dropUserFunction()
- engine()
- engineStats()
- executeClusterRebalance()
- executeTransaction()
- exists()
- explain()
- get()
- getClusterImbalance()
- getHotBackups()
- getLicense()
- getLogEntries()
- getLogLevel()
- getQueryCacheProperties()
- getService()
- getServiceConfiguration()
- getServiceDependencies()
- getServiceDocumentation()
- getServiceReadme()
- getServiceScripts()
- getUser()
- getUserAccessLevel()
- getUserDatabases()
- graph()
- graphs()
- installService()
- job()
- killQuery()
- listAnalyzers()
- listCollections()
- listCompletedJobs()
- listDatabases()
- listGraphs()
- listLogMessages()
- listPendingJobs()
- listQueryCacheEntries()
- listRunningQueries()
- listServices()
- listSlowQueries()
- listTransactions()
- listUserDatabases()
- listUserFunctions()
- listUsers()
- listViews()
- login()
- name
- parse()
- query()
- queryRules()
- queryTracking()
- queueTime
- rebalanceCluster()
- removeUser()
- renameCollection()
- renameView()
- renewAuthToken()
- replaceService()
- replaceServiceConfiguration()
- replaceServiceDependencies()
- replaceUser()
- restoreHotBackup()
- route()
- runServiceScript()
- runServiceTests()
- setLicense()
- setLogLevel()
- setQueryCacheProperties()
- setResponseQueueTimeSamples()
- setServiceDevelopmentMode()
- setUserAccessLevel()
- shutdown()
- status()
- supportInfo()
- time()
- transaction()
- transactions()
- uninstallService()
- updateServiceConfiguration()
- updateServiceDependencies()
- updateUser()
- upgradeService()
- useBasicAuth()
- useBearerAuth()
- userDatabases()
- version()
- view()
- views()
- waitForPropagation()
- withTransaction()
Functions
function aql
aql: <T = any>( templateStrings: TemplateStringsArray, ...args: AqlValue[]) => AqlQuery<T>;
Template string handler (template tag) for AQL queries.
The
aql
tag can be used to write complex AQL queries as multi-line strings without having to worry aboutbindVars
and the distinction between collections and regular parameters.Tagged template strings will return an AqlQuery object with
query
andbindVars
attributes reflecting any interpolated values.Any collections.ArangoCollection instance used in a query string will be recognized as a collection reference and generate an AQL collection bind parameter instead of a regular AQL value bind parameter.
**Note**: you should always use the
aql
template tag when writing dynamic AQL queries instead of using untagged (normal) template strings. Untagged template strings will inline any interpolated values and return a plain string as result. Theaql
template tag will only inline references to the interpolated values and produce an AQL query object containing both the query and the values. This prevents most injection attacks when using untrusted values in dynamic queries.Example 1
// Some user-supplied string that may be maliciousconst untrustedValue = req.body.email;// Without aql tag: BAD! DO NOT DO THIS!const badQuery = `FOR user IN usersFILTER user.email == "${untrustedValue}"RETURN user`;// e.g. if untrustedValue is '" || user.admin == true || "':// Query:// FOR user IN users// FILTER user.email == "" || user.admin == true || ""// RETURN user// With the aql tag: GOOD! MUCH SAFER!const betterQuery = aql`FOR user IN usersFILTER user.email == ${untrustedValue}RETURN user`;// Query:// FOR user IN users// FILTER user.email == @value0// RETURN user// Bind parameters:// value0 -> untrustedValueExample 2
const collection = db.collection("some-collection");const minValue = 23;const result = await db.query(aql`FOR d IN ${collection}FILTER d.num > ${minValue}RETURN d`);// Equivalent raw query objectconst result2 = await db.query({query: `FOR d IN @@collectionFILTER d.num > @minValueRETURN d`,bindVars: {"@collection": collection.name,minValue: minValue}});Example 3
const collection = db.collection("some-collection");const color = "green";const filter = aql`FILTER d.color == ${color}'`;const result = await db.query(aql`FOR d IN ${collection}${filter}RETURN d`);
function arangojs
arangojs: { (config?: configuration.ConfigOptions): databases.Database; (url: string | string[], name?: string): databases.Database;};
Creates a new
Database
instance with its own connection pool.This is a wrapper function for the .
Parameter config
An object with configuration options.
Example 1
const db = arangojs({url: "http://127.0.0.1:8529",databaseName: "myDatabase",auth: { username: "admin", password: "hunter2" },});Creates a new
Database
instance with its own connection pool.This is a wrapper function for the .
Parameter url
Base URL of the ArangoDB server or list of server URLs. Equivalent to the
url
option in configuration.ConfigOptions.Example 1
const db = arangojs("http://127.0.0.1:8529", "myDatabase");db.useBasicAuth("admin", "hunter2");
Classes
class Database
class Database {}
An object representing a single ArangoDB database. All arangojs collections, cursors, analyzers and so on are linked to a
Database
object.
constructor
constructor(config?: configuration.ConfigOptions);
Creates a new
Database
instance with its own connection pool.See also Database#database.
Parameter config
An object with configuration options.
Example 1
const db = new Database({url: "http://127.0.0.1:8529",databaseName: "my_database",auth: { username: "admin", password: "hunter2" },});
constructor
constructor(url: string | string[], name?: string);
Creates a new
Database
instance with its own connection pool.See also Database#database.
Parameter url
Base URL of the ArangoDB server or list of server URLs. Equivalent to the
url
option in configuration.ConfigOptions.Example 1
const db = new Database("http://127.0.0.1:8529", "my_database");db.useBasicAuth("admin", "hunter2");
property name
readonly name: string;
Name of the ArangoDB database this instance represents.
property queueTime
readonly queueTime: administration.QueueTimeMetrics;
Methods for accessing the server-reported queue times of the mostly recently received responses.
method acquireHostList
acquireHostList: (overwrite?: boolean) => 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 configuration.ConfigOptions.
For long-running processes communicating with an ArangoDB cluster it is recommended to run this method periodically (e.g. once per hour) to make sure new coordinators are picked up correctly and can be used for fail-over or load balancing.
Parameter overwrite
If set to
true
, the existing host list will be replaced instead of extended.Example 1
const db = new Database();const interval = setInterval(() => db.acquireHostList(),5 * 60 * 1000 // every 5 minutes);// laterclearInterval(interval);system.close();
method analyzer
analyzer: (analyzerName: string) => analyzers.Analyzer;
Returns an analyzers.Analyzer instance representing the Analyzer with the given
analyzerName
.Example 1
const db = new Database();const analyzer = db.analyzer("some-analyzer");const info = await analyzer.get();
method analyzers
analyzers: () => Promise<analyzers.Analyzer[]>;
Fetches all Analyzers visible in the database and returns an array of analyzers.Analyzer instances for those Analyzers.
See also Database#listAnalyzers.
Example 1
const db = new Database();const analyzers = await db.analyzers();// analyzers is an array of Analyzer instances
method availability
availability: (graceful?: boolean) => Promise<administration.ServerAvailability>;
Fetches availability information about the server.
Parameter graceful
If set to
true
, the method will always returnfalse
instead of throwing an error; otherwisefalse
will only be returned when the server responds with a 503 status code or an ArangoDB error with a code of 503, such as during shutdown.Example 1
const availability = await db.availability();// availability is either "default", "readonly", or false
method beginTransaction
beginTransaction: { ( collections: transactions.TransactionCollectionOptions, options?: transactions.TransactionOptions ): Promise<transactions.Transaction>; ( collections: (string | collections.ArangoCollection)[], options?: transactions.TransactionOptions ): Promise<transactions.Transaction>; ( collection: string | collections.ArangoCollection, options?: transactions.TransactionOptions ): Promise<transactions.Transaction>;};
Begins a new streaming transaction for the given collections, then returns a transactions.Transaction instance for the transaction.
Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.Parameter collections
Collections involved in the transaction.
Parameter options
Options for the transaction.
Example 1
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();Begins a new streaming transaction for the given collections, then returns a transactions.Transaction instance for the transaction.
Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.Parameter collections
Collections that can be read from and written to during the transaction.
Parameter options
Options for the transaction.
Example 1
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();Begins a new streaming transaction for the given collections, then returns a transactions.Transaction instance for the transaction.
The Collection can be specified as a collection name (string) or an object implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.Parameter collection
A collection that can be read from and written to during the transaction.
Parameter options
Options for the transaction.
Example 1
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();
method clearQueryCache
clearQueryCache: () => Promise<void>;
Clears the AQL query results cache of the current database.
Example 1
const db = new Database();await db.clearQueryCache();// Cache is now cleared
method clearSlowQueries
clearSlowQueries: () => Promise<void>;
Clears the list of recent slow queries.
See also Database#listSlowQueries.
Example 1
const db = new Database();await db.clearSlowQueries();// Slow query list is now cleared
method clearUserAccessLevel
clearUserAccessLevel: ( username: string, options: users.UserAccessLevelOptions) => Promise<connection.ArangoApiResponse<Record<string, users.AccessLevel>>>;
Clears the given ArangoDB user's access level for the database, or the given collection in the given database.
Parameter username
Name of the ArangoDB user to clear the access level for.
Parameter options
Database and/or collection to clear the access level for.
Example 1
const db = new Database();await db.clearUserAccessLevel("steve");// The access level of the user "steve" has been cleared for the current// database.Example 2
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 3
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 4
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 5
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 6
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".
method 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 1
const db = new Database();const sessions = db.collection("sessions");// Clean up expired sessions once per hoursetInterval(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 usedsystem.close();}, 1000 * 60 * 60);
method collection
collection: < EntryResultType extends Record<string, any> = any, EntryInputType extends Record<string, any> = EntryResultType>( collectionName: string) => collections.DocumentCollection<EntryResultType, EntryInputType> & collections.EdgeCollection<EntryResultType, EntryInputType>;
Returns a
Collection
instance for the given collection name.In TypeScript the collection implements both the collections.DocumentCollection and collections.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.
Parameter EntryResultType
Type to represent document contents returned by the server (including computed properties).
Parameter EntryInputType
Type to represent document contents passed when inserting or replacing documents (without computed properties).
Parameter collectionName
Name of the edge collection.
Example 1
const db = new Database();const collection = db.collection("potatoes");Example 2
interface Person {name: string;}const db = new Database();const persons = db.collection<Person>("persons");Example 3
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>;
method collections
collections: ( excludeSystem?: boolean) => Promise<Array<collections.DocumentCollection & collections.EdgeCollection>>;
Fetches all collections from the database and returns an array of
Collection
instances.In TypeScript these instances implement both the collections.DocumentCollection and collections.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.
See also Database#listCollections.
Parameter excludeSystem
Whether system collections should be excluded.
Example 1
const db = new Database();const collections = await db.collections();// collections is an array of DocumentCollection and EdgeCollection// instances not including system collectionsExample 2
const db = new Database();const collections = await db.collections(false);// collections is an array of DocumentCollection and EdgeCollection// instances including system collections
method commitLocalServiceState
commitLocalServiceState: (replace?: boolean) => Promise<void>;
Writes all locally available services to the database and updates any service bundles missing in the database.
Parameter replace
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.Example 1
await db.commitLocalServiceState();// all services available on the coordinator have been written to the dbExample 2
await db.commitLocalServiceState(true);// all service conflicts have been resolved in favor of this coordinator
method compact
compact: (options?: administration.CompactOptions) => Promise<void>;
Compacts all databases on the server.
Parameter options
Options for compacting the databases.
method computeClusterRebalance
computeClusterRebalance: ( options: cluster.ClusterRebalanceOptions) => Promise<cluster.ClusterRebalanceResult>;
Computes a set of move shard operations to rebalance the cluster.
Example 1
const db = new Database();const result = await db.computerClusterRebalance({moveLeaders: true,moveFollowers: true});if (result.moves.length) {await db.executeClusterRebalance(result.moves);}
method createAnalyzer
createAnalyzer: ( analyzerName: string, options: analyzers.CreateAnalyzerOptions) => Promise<analyzers.Analyzer>;
Creates a new Analyzer with the given
analyzerName
andoptions
, then returns an analyzers.Analyzer instance for the new Analyzer.Parameter analyzerName
Name of the Analyzer.
Parameter options
An object defining the properties of the Analyzer.
Example 1
const db = new Database();const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });// the identity Analyzer "potatoes" now exists
method createCollection
createCollection: { < EntryResultType extends Record<string, any> = any, EntryInputType extends Record<string, any> = EntryResultType >( collectionName: string, options?: collections.CreateCollectionOptions & { type?: collections.CollectionType.DOCUMENT_COLLECTION; } ): Promise<collections.DocumentCollection<EntryResultType, EntryInputType>>; < EntryResultType extends Record<string, any> = any, EntryInputType extends Record<string, any> = EntryResultType >( collectionName: string, options: collections.CollectionPropertiesOptions & { isSystem?: boolean; keyOptions?: collections.CollectionKeyOptions; waitForSyncReplication?: boolean; enforceReplicationFactor?: boolean; numberOfShards?: number; shardKeys?: string[]; shardingStrategy?: collections.ShardingStrategy; distributeShardsLike?: string; smartJoinAttribute?: string; smartGraphAttribute?: string; } & { type: collections.CollectionType.EDGE_COLLECTION } ): Promise<collections.EdgeCollection<EntryResultType, EntryInputType>>;};
Creates a new collection with the given
collectionName
andoptions
, then returns a collections.DocumentCollection instance for the new collection.Parameter EntryResultType
Type to represent document contents returned by the server (including computed properties).
Parameter EntryInputType
Type to represent document contents passed when inserting or replacing documents (without computed properties).
Parameter collectionName
Name of the new collection.
Parameter options
Options for creating the collection.
Example 1
const db = new Database();const documents = db.createCollection("persons");Example 2
interface Person {name: string;}const db = new Database();const documents = db.createCollection<Person>("persons");Creates a new edge collection with the given
collectionName
andoptions
, then returns an collections.EdgeCollection instance for the new edge collection.Parameter EntryResultType
Type to represent edge document contents returned by the server (including computed properties).
Parameter EntryInputType
Type to represent edge document contents passed when inserting or replacing documents (without computed properties).
Parameter collectionName
Name of the new collection.
Parameter options
Options for creating the collection.
Example 1
const db = new Database();const edges = db.createCollection("friends", {type: CollectionType.EDGE_COLLECTION});Example 2
interface Friend {startDate: number;endDate?: number;}const db = new Database();const edges = db.createCollection<Friend>("friends", {type: CollectionType.EDGE_COLLECTION});
method createDatabase
createDatabase: { (databaseName: string, options?: CreateDatabaseOptions): Promise<Database>; ( databaseName: string, users: users.CreateDatabaseUserOptions[] ): Promise<Database>;};
Creates a new database with the given
databaseName
with the givenoptions
and returns aDatabase
instance for that database.Parameter databaseName
Name of the database to create.
Parameter options
Options for creating the database.
Example 1
const db = new Database();const info = await db.createDatabase("mydb", {users: [{ username: "root" }]});// the database has been createdCreates a new database with the given
databaseName
with the givenusers
and returns aDatabase
instance for that database.Parameter databaseName
Name of the database to create.
Parameter users
Database users to create with the database.
Example 1
const db = new Database();const info = await db.createDatabase("mydb", [{ username: "root" }]);// the database has been created
method createEdgeCollection
createEdgeCollection: < EntryResultType extends Record<string, any> = any, EntryInputType extends Record<string, any> = EntryResultType>( collectionName: string, options?: collections.CreateCollectionOptions) => Promise<collections.EdgeCollection<EntryResultType, EntryInputType>>;
Creates a new edge collection with the given
collectionName
andoptions
, then returns an collections.EdgeCollection instance for the new edge collection.This is a convenience method for calling Database#createCollection with
options.type
set toEDGE_COLLECTION
.Parameter EntryResultType
Type to represent edge document contents returned by the server (including computed properties).
Parameter EntryInputType
Type to represent edge document contents passed when inserting or replacing documents (without computed properties).
Parameter collectionName
Name of the new collection.
Parameter options
Options for creating the collection.
Example 1
const db = new Database();const edges = db.createEdgeCollection("friends");Example 2
interface Friend {startDate: number;endDate?: number;}const db = new Database();const edges = db.createEdgeCollection<Friend>("friends");
method createGraph
createGraph: ( graphName: string, edgeDefinitions: graphs.EdgeDefinitionOptions[], options?: graphs.CreateGraphOptions) => Promise<graphs.Graph>;
Creates a graph with the given
graphName
andedgeDefinitions
, then returns a graphs.Graph instance for the new graph.Parameter graphName
Name of the graph to be created.
Parameter edgeDefinitions
An array of edge definitions.
Parameter options
An object defining the properties of the graph.
method createHotBackup
createHotBackup: ( options?: hotBackups.HotBackupOptions) => Promise<hotBackups.HotBackupResult>;
(Enterprise Edition only.) Creates a hot backup of the entire ArangoDB deployment including all databases, collections, etc.
Returns an object describing the backup result.
Parameter options
Options for creating the backup.
Example 1
const info = await db.createHotBackup();// a hot backup has been created
method createJob
createJob: <T>(callback: () => Promise<T>) => Promise<jobs.Job<T>>;
Creates an async job by executing the given callback function. The first database request performed by the callback will be marked for asynchronous execution and its result will be made available as an async job.
Returns a jobs.Job instance that can be used to retrieve the result of the callback function once the request has been executed.
Parameter callback
Callback function to execute as an async job.
Example 1
const db = new Database();const job = await db.createJob(() => db.collections());while (!job.isLoaded) {await timeout(1000);await job.load();}// job.result is a list of Collection instances
method createUser
createUser: { (username: string, passwd: string): Promise< connection.ArangoApiResponse<users.ArangoUser> >; (username: string, options: users.UserOptions): Promise< connection.ArangoApiResponse<users.ArangoUser> >;};
Creates a new ArangoDB user with the given password.
Parameter username
Name of the ArangoDB user to create.
Parameter passwd
Password of the new ArangoDB user.
Example 1
const db = new Database();const user = await db.createUser("steve", "hunter2");// The user "steve" has been createdCreates a new ArangoDB user with the given options.
Parameter username
Name of the ArangoDB user to create.
Parameter options
Additional options for creating the ArangoDB user.
Example 1
const db = new Database();const user = await db.createUser("steve", { passwd: "hunter2" });// The user "steve" has been created
method createUserFunction
createUserFunction: ( name: string, code: string, isDeterministic?: boolean) => Promise<connection.ArangoApiResponse<{ 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.
Parameter name
A valid AQL function name. The function name must consist of at least two alphanumeric identifiers separated with double colons.
Parameter code
A string evaluating to a JavaScript function (not a JavaScript function object).
Parameter isDeterministic
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.Example 1
const db = new Database();await db.createUserFunction("ACME::ACCOUNTING::CALCULATE_VAT","(price) => price * 0.19");// Use the new function in an AQL query with template handler:const cursor = await db.query(aql`FOR product IN productsRETURN MERGE({ vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price) },product)`);// cursor is a cursor for the query result
method createView
createView: ( viewName: string, options: views.CreateViewOptions) => Promise<views.View>;
Creates a new View with the given
viewName
andoptions
, then returns a views.View instance for the new View.Parameter viewName
Name of the View.
Parameter options
An object defining the properties of the View.
Example 1
const db = new Database();const view = await db.createView("potatoes", { type: "arangosearch" });// the ArangoSearch View "potatoes" now exists
method database
database: (databaseName: string) => Database;
Creates a new
Database
instance for the givendatabaseName
that shares this database's connection pool.See also .
Parameter databaseName
Name of the database.
Example 1
const systemDb = new Database();const myDb = systemDb.database("my_database");
method databases
databases: () => Promise<Database[]>;
Fetches all databases from the server and returns an array of
Database
instances for those databases.See also Database#listDatabases and Database#userDatabases.
Example 1
const db = new Database();const names = await db.databases();// databases is an array of databases
method deleteAllJobResults
deleteAllJobResults: () => Promise<void>;
Deletes the results of all completed async jobs.
method deleteExpiredJobResults
deleteExpiredJobResults: (threshold: number) => Promise<void>;
Deletes the results of all completed async jobs created before the given threshold.
Parameter threshold
The expiration timestamp in milliseconds.
Example 1
const db = new Database();const ONE_WEEK = 7 * 24 * 60 * 60 * 1000;await db.deleteExpiredJobResults(Date.now() - ONE_WEEK);// all job results older than a week have been deleted
method deleteHotBackup
deleteHotBackup: (id: string) => Promise<void>;
(Enterprise Edition only.) Deletes a local hot backup.
Parameter id
The ID of the backup to delete.
Example 1
await db.deleteHotBackup("2023-09-19T15.38.21Z_example");// the backup has been deleted
method downloadService
downloadService: (mount: string) => Promise<Buffer | Blob>;
Retrieves a zip bundle containing the service files.
Returns a
Buffer
in node.js orBlob
in the browser.Parameter mount
The service's mount point, relative to the database.
Example 1
const db = new Database();const serviceBundle = await db.downloadService("/my-foxx");
method dropDatabase
dropDatabase: (databaseName: string) => Promise<boolean>;
Deletes the database with the given
databaseName
from the server.Parameter databaseName
Name of the database to delete.
Example 1
const db = new Database();await db.dropDatabase("mydb");// database "mydb" no longer exists
method dropUserFunction
dropUserFunction: ( name: string, group?: boolean) => Promise<connection.ArangoApiResponse<{ deletedCount: number }>>;
Deletes the AQL user function with the given name from the database.
Parameter name
The name of the user function to drop.
Parameter group
If set to
true
, all functions with a name starting withname
will be deleted, otherwise only the function with the exact name will be deleted.Example 1
const db = new Database();await db.dropUserFunction("ACME::ACCOUNTING::CALCULATE_VAT");// the function no longer exists
method engine
engine: () => Promise<administration.EngineInfo>;
Fetches storage engine information from the ArangoDB server.
Example 1
const db = new Database();const engine = await db.engine();// the engine object contains the storage engine information, e.g.// name: name of the storage engine
method engineStats
engineStats: () => Promise<administration.EngineStatsInfo>;
Fetches detailed storage engine performance and resource usage information from the ArangoDB server.
Example 1
const db = new Database();const stats = await db.engineStats();// the stats object contains the storage engine stats
method executeClusterRebalance
executeClusterRebalance: ( moves: cluster.ClusterRebalanceMove[]) => Promise<unknown>;
Executes the given cluster move shard operations.
Example 1
const db = new Database();const result = await db.computerClusterRebalance({moveLeaders: true,moveFollowers: true});if (result.moves.length) {await db.executeClusterRebalance(result.moves);}
method executeTransaction
executeTransaction: { ( collections: transactions.TransactionCollectionOptions & { allowImplicit?: boolean; }, action: string, options?: transactions.TransactionOptions & { params?: any } ): Promise<any>; ( collections: (string | collections.ArangoCollection)[], action: string, options?: transactions.TransactionOptions & { params?: any } ): Promise<any>; ( collection: string | collections.ArangoCollection, action: string, options?: transactions.TransactionOptions & { params?: any } ): Promise<any>;};
Performs a server-side JavaScript transaction and returns its return value.
Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.**Note**: The
action
function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via theparams
option.See the official ArangoDB documentation for [the JavaScript
@arangodb
module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html) for information about accessing the database from within ArangoDB's server-side JavaScript environment.Parameter collections
Collections involved in the transaction.
Parameter action
A string evaluating to a JavaScript function to be executed on the server.
Parameter options
Options for the transaction. If
options.allowImplicit
is specified, it will be used ifcollections.allowImplicit
was not specified.Example 1
const db = new Database();const action = `function(params) {// This code will be executed inside ArangoDB!const { query } = require("@arangodb");return query\`FOR user IN _usersFILTER 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 actionPerforms a server-side transaction and returns its return value.
Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.**Note**: The
action
function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via theparams
option. See the official ArangoDB documentation for [the JavaScript@arangodb
module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html) for information about accessing the database from within ArangoDB's server-side JavaScript environment.Parameter collections
Collections that can be read from and written to during the transaction.
Parameter action
A string evaluating to a JavaScript function to be executed on the server.
Parameter options
Options for the transaction.
Example 1
const db = new Database();const action = `function(params) {// This code will be executed inside ArangoDB!const { query } = require("@arangodb");return query\`FOR user IN _usersFILTER 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 actionPerforms a server-side transaction and returns its return value.
The Collection can be specified as a collection name (string) or an object implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.**Note**: The
action
function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via theparams
option. See the official ArangoDB documentation for [the JavaScript@arangodb
module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html) for information about accessing the database from within ArangoDB's server-side JavaScript environment.Parameter collection
A collection that can be read from and written to during the transaction.
Parameter action
A string evaluating to a JavaScript function to be executed on the server.
Parameter options
Options for the transaction.
Example 1
const db = new Database();const action = `function(params) {// This code will be executed inside ArangoDB!const { query } = require("@arangodb");return query\`FOR user IN _usersFILTER 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
method exists
exists: () => Promise<boolean>;
Checks whether the database exists.
Example 1
const db = new Database();const result = await db.exists();// result indicates whether the database exists
method explain
explain: { ( query: aql.AqlQuery, options?: queries.ExplainOptions & { allPlans?: false } ): Promise<connection.ArangoApiResponse<queries.SingleExplainResult>>; ( query: aql.AqlQuery<any>, options?: queries.ExplainOptions & { allPlans: true } ): Promise<connection.ArangoApiResponse<queries.MultiExplainResult>>; ( query: string | aql.AqlLiteral, bindVars?: Record<string, any>, options?: queries.ExplainOptions & { allPlans?: false } ): Promise<connection.ArangoApiResponse<queries.SingleExplainResult>>; ( query: string | aql.AqlLiteral, bindVars?: Record<string, any>, options?: queries.ExplainOptions & { allPlans: true } ): Promise<connection.ArangoApiResponse<queries.MultiExplainResult>>;};
Explains a database query using the given
query
.See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
Parameter query
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.
Parameter options
Options for explaining the query.
Example 1
const db = new Database();const collection = db.collection("some-collection");const explanation = await db.explain(aql`FOR doc IN ${collection}FILTER doc.flavor == "strawberry"RETURN doc._key`);Explains a database query using the given
query
.See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
Parameter query
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.
Parameter options
Options for explaining the query.
Example 1
const db = new Database();const collection = db.collection("some-collection");const explanation = await db.explain(aql`FOR doc IN ${collection}FILTER doc.flavor == "strawberry"RETURN doc._key`,{ allPlans: true });Explains a database query using the given
query
andbindVars
.See the aql.aql template string handler for a safer and easier alternative to passing strings directly.
Parameter query
An AQL query string.
Parameter bindVars
An object defining bind parameters for the query.
Parameter options
Options for explaining the query.
Example 1
const db = new Database();const collection = db.collection("some-collection");const explanation = await db.explain(`FOR doc IN @@collectionFILTER doc.flavor == "strawberry"RETURN doc._key`,{ "@collection": collection.name });Explains a database query using the given
query
andbindVars
.See the aql.aql template string handler for a safer and easier alternative to passing strings directly.
Parameter query
An AQL query string.
Parameter bindVars
An object defining bind parameters for the query.
Parameter options
Options for explaining the query.
Example 1
const db = new Database();const collection = db.collection("some-collection");const explanation = await db.explain(`FOR doc IN @@collectionFILTER doc.flavor == "strawberry"RETURN doc._key`,{ "@collection": collection.name },{ allPlans: true });
method get
get: () => Promise<DatabaseDescription>;
Fetches the database description for the active database from the server.
Example 1
const db = new Database();const info = await db.get();// the database exists
method getClusterImbalance
getClusterImbalance: () => Promise<cluster.ClusterRebalanceState>;
Computes the current cluster imbalance.
Example 1
const db = new Database();const imbalance = await db.getClusterImbalance();
method getHotBackups
getHotBackups: (id?: string | string[]) => Promise<hotBackups.HotBackupList>;
(Enterprise Edition only.) Retrieves a list of all locally found hot backups.
Parameter id
If specified, only the backup with the given ID will be returned.
Example 1
const backups = await db.getHotBackups();for (const backup of backups.list) {console.log(backup.id);}
method getLicense
getLicense: () => Promise<administration.LicenseInfo>;
Fetches the license information and status of an Enterprise Edition server.
method getLogEntries
getLogEntries: (options?: logs.LogEntriesOptions) => Promise<logs.LogEntries>;
Retrieves the log messages from the server's global log.
Parameter options
Options for retrieving the log entries.
Example 1
const log = await db.getLogEntries();for (let i = 0; i < log.totalAmount; i++) {console.log(`${new Date(log.timestamp[i] * 1000).toISOString()} - [${LogLevel[log.level[i]]}] ${log.text[i]} (#${log.lid[i]})`);}
method getLogLevel
getLogLevel: () => Promise<Record<string, logs.LogLevelSetting>>;
Retrieves the server's current log level for each topic.
Example 1
const levels = await db.getLogLevel();console.log(levels.request); // log level for incoming requests
method getQueryCacheProperties
getQueryCacheProperties: () => Promise<queries.QueryCacheProperties>;
Fetches the global properties for the AQL query results cache.
Example 1
const db = new Database();const properties = await db.getQueryCacheProperties();console.log(properties);
method getService
getService: (mount: string) => Promise<services.ServiceDescription>;
Retrieves information about a mounted service.
Parameter mount
The service's mount point, relative to the database.
Example 1
const db = new Database();const info = await db.getService("/my-service");// info contains detailed information about the service
method getServiceConfiguration
getServiceConfiguration: { (mount: string, minimal?: false): Promise< Record<string, services.ServiceConfiguration> >; (mount: string, minimal: true): Promise<Record<string, any>>;};
Retrieves information about the service's configuration options and their current values.
See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.
Parameter mount
The service's mount point, relative to the database.
Parameter minimal
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.Example 1
const db = new Database();const config = await db.getServiceConfiguration("/my-service");for (const [key, option] of Object.entries(config)) {console.log(`${option.title} (${key}): ${option.current}`);}Retrieves information about the service's configuration options and their current values.
See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.
Parameter mount
The service's mount point, relative to the database.
Parameter minimal
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.Example 1
const db = new Database();const config = await db.getServiceConfiguration("/my-service", true);for (const [key, value] of Object.entries(config)) {console.log(`${key}: ${value}`);}
method getServiceDependencies
getServiceDependencies: { (mount: string, minimal?: false): Promise< Record< string, services.SingleServiceDependency | services.MultiServiceDependency > >; (mount: string, minimal: true): Promise<Record<string, string | string[]>>;};
Retrieves information about the service's dependencies and their current mount points.
See also Database#replaceServiceDependencies and Database#updateServiceDependencies.
Parameter mount
The service's mount point, relative to the database.
Parameter minimal
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.Example 1
const db = new Database();const deps = await db.getServiceDependencies("/my-service");for (const [key, dep] of Object.entries(deps)) {console.log(`${dep.title} (${key}): ${dep.current}`);}Retrieves information about the service's dependencies and their current mount points.
See also Database#replaceServiceDependencies and Database#updateServiceDependencies.
Parameter mount
The service's mount point, relative to the database.
Parameter minimal
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.Example 1
const db = new Database();const deps = await db.getServiceDependencies("/my-service", true);for (const [key, value] of Object.entries(deps)) {console.log(`${key}: ${value}`);}
method getServiceDocumentation
getServiceDocumentation: (mount: string) => Promise<services.SwaggerJson>;
Retrieves an Open API compatible Swagger API description object for the service installed at the given mount point.
Parameter mount
The service's mount point, relative to the database.
Example 1
const db = new Database();const spec = await db.getServiceDocumentation("/my-service");// spec is a Swagger API description of the service
method getServiceReadme
getServiceReadme: (mount: string) => Promise<string | undefined>;
Retrieves the text content of the service's
README
orREADME.md
file.Returns
undefined
if no such file could be found.Parameter mount
The service's mount point, relative to the database.
Example 1
const db = new Database();const readme = await db.getServiceReadme("/my-service");if (readme !== undefined) console.log(readme);else console.warn(`No README found.`)
method getServiceScripts
getServiceScripts: (mount: string) => Promise<Record<string, string>>;
Retrieves an object mapping script names to their human readable representations, as defined in the service manifest's "scripts" section.
Parameter mount
The service's mount point, relative to the database.
Example 1
const db = new Database();const scripts = await db.getServiceScripts("/my-service");for (const [name, title] of Object.entries(scripts)) {console.log(`${name}: ${title}`);}
method getUser
getUser: ( username: string) => Promise<connection.ArangoApiResponse<users.ArangoUser>>;
Fetches the user data of a single ArangoDB user.
Parameter username
Name of the ArangoDB user to fetch.
Example 1
const db = new Database();const user = await db.getUser("steve");// user is the user object for the user named "steve"
method getUserAccessLevel
getUserAccessLevel: ( username: string, options: users.UserAccessLevelOptions) => Promise<users.AccessLevel>;
Fetches the given ArangoDB user's access level for the database, or the given collection in the given database.
Parameter username
Name of the ArangoDB user to fetch the access level for.
Parameter options
Collection and/or database to fetch the access level for.
Example 1
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 2
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 3
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 4
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 5
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 6
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".
method getUserDatabases
getUserDatabases: { (username: string, full?: false): Promise<Record<string, users.AccessLevel>>; (username: string, full: true): Promise< Record< string, { permission: users.AccessLevel; collections: Record<string, 'undefined' | users.AccessLevel>; } > >;};
Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases.
Parameter username
Name of the ArangoDB user to fetch the access levels for.
Parameter full
Whether access levels for collections should be included.
Example 1
const db = new Database();const accessLevels = await db.getUserDatabases("steve");for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {console.log(`${databaseName}: ${accessLevel}`);}Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases and the collections within each database.
Parameter username
Name of the ArangoDB user to fetch the access levels for.
Parameter full
Whether access levels for collections should be included.
Example 1
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}`);}}
method graph
graph: (graphName: string) => graphs.Graph;
Returns a graphs.Graph instance representing the graph with the given
graphName
.Parameter graphName
Name of the graph.
Example 1
const db = new Database();const graph = db.graph("some-graph");
method graphs
graphs: () => Promise<graphs.Graph[]>;
Fetches all graphs from the database and returns an array of graphs.Graph instances for those graphs.
See also Database#listGraphs.
Example 1
const db = new Database();const graphs = await db.graphs();// graphs is an array of Graph instances
method installService
installService: ( mount: string, source: Blob | string, options?: services.InstallServiceOptions) => Promise<services.ServiceDescription>;
Installs a new service.
Parameter mount
The service's mount point, relative to the database.
Parameter source
The service bundle to install.
Parameter options
Options for installing the service.
Example 1
const db = new Database();// Using a Buffer in Node.js as sourceconst source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);const info = await db.installService("/hello", source);Example 2
const db = new Database();// Using a Blob in Node.js as sourceconst source = await fs.openAsBlob("./my-foxx-service.zip");const info = await db.installService("/hello", source);Example 3
const db = new Database();// Using a File from a browser file input as sourceconst element = document.getElementById("my-file-input");const source = element.files[0];const info = await db.installService("/hello", source);
method job
job: (jobId: string) => jobs.Job;
Returns a jobs.Job instance for the given
jobId
.Parameter jobId
ID of the async job.
Example 1
const db = new Database();const job = db.job("12345");
method killQuery
killQuery: (queryId: string) => Promise<void>;
Kills a running query with the given
queryId
.See also Database#listRunningQueries.
Parameter queryId
The ID of a currently running query.
Example 1
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);}}));
method listAnalyzers
listAnalyzers: () => Promise<analyzers.AnalyzerDescription[]>;
Fetches all Analyzers visible in the database and returns an array of Analyzer descriptions.
See also Database#analyzers.
Example 1
const db = new Database();const analyzers = await db.listAnalyzers();// analyzers is an array of Analyzer descriptions
method listCollections
listCollections: ( excludeSystem?: boolean) => Promise<collections.CollectionDescription[]>;
Fetches all collections from the database and returns an array of collection descriptions.
See also Database#collections.
Parameter excludeSystem
Whether system collections should be excluded.
Example 1
const db = new Database();const collections = await db.listCollections();// collections is an array of collection descriptions// not including system collectionsExample 2
const db = new Database();const collections = await db.listCollections(false);// collections is an array of collection descriptions// including system collections
method listCompletedJobs
listCompletedJobs: () => Promise<string[]>;
Returns a list of the IDs of all currently available completed async jobs.
Example 1
const db = new Database();const completedJobs = await db.listCompletedJobs();console.log(completedJobs); // e.g. ["12345", "67890"]
method 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 1
const db = new Database();const names = await db.listDatabases();// databases is an array of database names
method listGraphs
listGraphs: () => Promise<graphs.GraphDescription[]>;
Fetches all graphs from the database and returns an array of graph descriptions.
See also Database#graphs.
Example 1
const db = new Database();const graphs = await db.listGraphs();// graphs is an array of graph descriptions
method listLogMessages
listLogMessages: ( options?: logs.LogEntriesOptions) => Promise<logs.LogMessage[]>;
Retrieves the log messages from the server's global log.
Parameter options
Options for retrieving the log entries.
Example 1
const messages = await db.listLogMessages();for (const m of messages) {console.log(`${m.date} - [${m.level}] ${m.message} (#${m.id})`);}Deprecated
This endpoint has been deprecated in ArangoDB 3.8. Use Database#getLogEntries instead.
method listPendingJobs
listPendingJobs: () => Promise<string[]>;
Returns a list of the IDs of all currently pending async jobs.
Example 1
const db = new Database();const pendingJobs = await db.listPendingJobs();console.log(pendingJobs); // e.g. ["12345", "67890"]
method listQueryCacheEntries
listQueryCacheEntries: () => Promise<queries.QueryCacheEntry[]>;
Fetches a list of all entries in the AQL query results cache of the current database.
Example 1
const db = new Database();const entries = await db.listQueryCacheEntries();console.log(entries);
method listRunningQueries
listRunningQueries: () => Promise<queries.QueryDescription[]>;
Fetches a list of information for all currently running queries.
See also Database#listSlowQueries and Database#killQuery.
Example 1
const db = new Database();const queries = await db.listRunningQueries();
method listServices
listServices: (excludeSystem?: boolean) => Promise<services.ServiceSummary[]>;
Fetches a list of all installed service.
Parameter excludeSystem
Whether system services should be excluded.
Example 1
const db = new Database();const services = await db.listServices();Example 2
const db = new Database();const services = await db.listServices(false); // all services
method listSlowQueries
listSlowQueries: () => Promise<queries.QueryDescription[]>;
Fetches a list of information for all recent slow queries.
See also Database#listRunningQueries and Database#clearSlowQueries.
Example 1
const db = new Database();const queries = await db.listSlowQueries();// Only works if slow query tracking is enabled
method listTransactions
listTransactions: () => Promise<transactions.TransactionDescription[]>;
Fetches all active transactions from the database and returns an array of transaction descriptions.
See also Database#transactions.
Example 1
const db = new Database();const transactions = await db.listTransactions();// transactions is an array of transaction descriptions
method 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 1
const db = new Database();const names = await db.listUserDatabases();// databases is an array of database names
method listUserFunctions
listUserFunctions: () => Promise<queries.UserFunctionDescription[]>;
Fetches a list of all AQL user functions registered with the database.
Example 1
const db = new Database();const functions = await db.listUserFunctions();const names = functions.map(fn => fn.name);
method listUsers
listUsers: () => Promise<users.ArangoUser[]>;
Fetches all ArangoDB users visible to the authenticated user and returns an array of user objects.
Example 1
const db = new Database();const users = await db.listUsers();// users is an array of user objects
method listViews
listViews: () => Promise<views.ViewDescription[]>;
Fetches all Views from the database and returns an array of View descriptions.
See also Database#views.
Example 1
const db = new Database();const views = await db.listViews();// views is an array of View descriptions
method 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.
Parameter username
The username to authenticate with.
Parameter password
The password to authenticate with.
Example 1
const db = new Database();await db.login("admin", "hunter2");// with an authentication token for the "admin" user.
method parse
parse: ( query: string | aql.AqlQuery | aql.AqlLiteral) => Promise<queries.ParseResult>;
Parses the given query and returns the result.
See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
Parameter query
An AQL query string or an object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.
Example 1
const db = new Database();const collection = db.collection("some-collection");const ast = await db.parse(aql`FOR doc IN ${collection}FILTER doc.flavor == "strawberry"RETURN doc._key`);aql.
method query
query: { <T = any>(query: aql.AqlQuery<T>, options?: queries.QueryOptions): Promise< cursors.Cursor<T> >; <T = any>( query: string | aql.AqlLiteral, bindVars?: Record<string, any>, options?: queries.QueryOptions ): Promise<cursors.Cursor<T>>;};
Performs a database query using the given
query
, then returns a new cursors.Cursor instance for the result set.See the aql.aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
**Note**: When executing a query in a streaming transaction using the
step
method, the resulting cursor will be bound to that transaction and you do not need to use thestep
method to consume it.Parameter query
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql.aql template string.
Parameter options
Options for the query execution.
Example 1
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 resultExample 2
const db = new Database();const active = true;const Users = db.collection("_users");// Using an object with a regular multi-line stringconst cursor = await db.query({query: `FOR u IN @@usersFILTER u.authData.active == @activeRETURN u.user`,bindVars: { active: active, "@users": Users.name }});Performs a database query using the given
query
andbindVars
, then returns a new cursors.Cursor instance for the result set.See the aql.aql template string handler for a safer and easier alternative to passing strings directly.
**Note**: When executing a query in a streaming transaction using the
step
method, the resulting cursor will be bound to that transaction and you do not need to use thestep
method to consume it.Parameter query
An AQL query string.
Parameter bindVars
An object defining bind parameters for the query.
Parameter options
Options for the query execution.
Example 1
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 @@usersFILTER u.authData.active == @activeRETURN u.user`,{ active: active, "@users": Users.name });Example 2
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 stringaql.literal(`FOR u IN @@usersFILTER u.authData.active == @activeRETURN u.user`),{ active: active, "@users": Users.name });
method queryRules
queryRules: () => Promise<queries.QueryOptimizerRule[]>;
Fetches the available optimizer rules.
Example 1
const db = new Database();const rules = await db.queryRules();for (const rule of rules) {console.log(rule.name);}
method queryTracking
queryTracking: { (): Promise<queries.QueryTrackingInfo>; (options: queries.QueryTrackingOptions): Promise<queries.QueryTrackingInfo>;};
Fetches the query tracking properties.
Example 1
const db = new Database();const tracking = await db.queryTracking();console.log(tracking.enabled);Modifies the query tracking properties.
Parameter options
Options for query tracking.
Example 1
const db = new Database();// track up to 5 slow queries exceeding 5 seconds execution timeawait db.setQueryTracking({enabled: true,trackSlowQueries: true,maxSlowQueries: 5,slowQueryThreshold: 5});
method rebalanceCluster
rebalanceCluster: ( options: cluster.ClusterRebalanceOptions) => Promise<cluster.ClusterRebalanceResult>;
Computes a set of move shard operations to rebalance the cluster and executes them.
Parameter options
Options for rebalancing the cluster.
Example 1
const db = new Database();const result = await db.rebalanceCluster({moveLeaders: true,moveFollowers: true});// The cluster is now rebalanced.
method removeUser
removeUser: (username: string) => Promise<void>;
Removes the ArangoDB user with the given username from the server.
Parameter username
Name of the ArangoDB user to remove.
Example 1
const db = new Database();await db.removeUser("steve");// The user "steve" has been removed
method renameCollection
renameCollection: ( collectionName: string, newName: string) => Promise<connection.ArangoApiResponse<collections.CollectionDescription>>;
Renames the collection
collectionName
tonewName
.Additionally removes any stored
Collection
instance forcollectionName
from theDatabase
instance's internal cache.**Note**: Renaming collections may not be supported when ArangoDB is running in a cluster configuration.
Parameter collectionName
Current name of the collection.
Parameter newName
The new name of the collection.
method renameView
renameView: ( viewName: string, newName: string) => Promise<connection.ArangoApiResponse<views.ViewDescription>>;
Renames the view
viewName
tonewName
.Additionally removes any stored views.View instance for
viewName
from theDatabase
instance's internal cache.**Note**: Renaming views may not be supported when ArangoDB is running in a cluster configuration.
Parameter viewName
Current name of the view.
Parameter newName
The new name of the view.
method renewAuthToken
renewAuthToken: () => Promise<string | null>;
Attempts to renew the authentication token passed to Database#useBearerAuth or returned and used by Database#login. If a new authentication token is issued, it will be used for future requests and returned.
Example 1
const db = new Database();await db.login("admin", "hunter2");// ... later ...const newToken = await db.renewAuthToken();if (!newToken) // no new token issued
method replaceService
replaceService: ( mount: string, source: Blob | string, options?: services.ReplaceServiceOptions) => Promise<services.ServiceDescription>;
Replaces an existing service with a new service by completely removing the old service and installing a new service at the same mount point.
Parameter mount
The service's mount point, relative to the database.
Parameter source
The service bundle to install.
Parameter options
Options for replacing the service.
Example 1
const db = new Database();// Using a Buffer in Node.js as sourceconst source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);const info = await db.replaceService("/hello", source);Example 2
const db = new Database();// Using a Blob in Node.js as sourceconst source = await fs.openAsBlob("./my-foxx-service.zip");const info = await db.replaceService("/hello", source);Example 3
const db = new Database();// Using a File from a browser file input as sourceconst element = document.getElementById("my-file-input");const source = element.files[0];const info = await db.replaceService("/hello", source);
method replaceServiceConfiguration
replaceServiceConfiguration: { (mount: string, cfg: Record<string, any>, minimal?: false): Promise< Record<string, services.ServiceConfiguration & { warning?: string }> >; (mount: string, cfg: Record<string, any>, minimal: true): Promise<{ values: Record<string, any>; warnings: Record<string, string>; }>;};
Replaces the configuration of the given service, discarding any existing values for options not specified.
See also Database#updateServiceConfiguration and Database#getServiceConfiguration.
Parameter mount
The service's mount point, relative to the database.
Parameter cfg
An object mapping configuration option names to values.
Parameter minimal
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.Example 1
const db = new Database();const config = { currency: "USD", locale: "en-US" };const info = await db.replaceServiceConfiguration("/my-service", config);for (const [key, option] of Object.entries(info)) {console.log(`${option.title} (${key}): ${option.value}`);if (option.warning) console.warn(`Warning: ${option.warning}`);}Replaces the configuration of the given service, discarding any existing values for options not specified.
See also Database#updateServiceConfiguration and Database#getServiceConfiguration.
Parameter mount
The service's mount point, relative to the database.
Parameter cfg
An object mapping configuration option names to values.
Parameter minimal
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.Example 1
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]}`);}
method replaceServiceDependencies
replaceServiceDependencies: { (mount: string, deps: Record<string, string>, minimal?: false): Promise< Record< string, ( | services.SingleServiceDependency | services.MultiServiceDependency ) & { warning?: string } > >; (mount: string, deps: Record<string, string>, minimal: true): Promise<{ values: Record<string, string>; warnings: Record<string, string>; }>;};
Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.
See also Database#updateServiceDependencies and Database#getServiceDependencies.
Parameter mount
The service's mount point, relative to the database.
Parameter deps
An object mapping dependency aliases to mount points.
Parameter minimal
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.Example 1
const db = new Database();const deps = { mailer: "/mailer-api", auth: "/remote-auth" };const info = await db.replaceServiceDependencies("/my-service", deps);for (const [key, dep] of Object.entries(info)) {console.log(`${dep.title} (${key}): ${dep.current}`);if (dep.warning) console.warn(`Warning: ${dep.warning}`);}Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.
See also Database#updateServiceDependencies and Database#getServiceDependencies.
Parameter mount
The service's mount point, relative to the database.
Parameter deps
An object mapping dependency aliases to mount points.
Parameter minimal
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.Example 1
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]}`);}
method replaceUser
replaceUser: ( username: string, options: users.UserOptions) => Promise<connection.ArangoApiResponse<users.ArangoUser>>;
Replaces the ArangoDB user's option with the new options.
Parameter username
Name of the ArangoDB user to modify.
Parameter options
New options to replace the user's existing options.
Example 1
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
method restoreHotBackup
restoreHotBackup: (id: string) => Promise<string>;
(Enteprise Edition only.) Restores a consistent local hot backup.
Returns the directory path of the restored backup.
Parameter id
The ID of the backup to restore.
Example 1
await db.restoreHotBackup("2023-09-19T15.38.21Z_example");// the backup has been restored
method route
route: ( path?: string, headers?: Headers | Record<string, string>) => routes.Route;
Returns a new routes.Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.
Parameter path
The database-relative URL of the route. Defaults to the database API root.
Parameter headers
Default headers that should be sent with each request to the route.
Example 1
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"}'
method runServiceScript
runServiceScript: (mount: string, name: string, params?: any) => Promise<any>;
Executes a service script and retrieves its result exposed as
module.exports
(if any).Parameter mount
The service's mount point, relative to the database.
Parameter name
Name of the service script to execute as defined in the service manifest.
Parameter params
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.Example 1
const db = new Database();const result = await db.runServiceScript("/my-service","create-user",{username: "service_admin",password: "hunter2"});
method runServiceTests
runServiceTests: { ( mount: string, options?: { reporter?: 'default'; idiomatic?: false; filter?: string } ): Promise<services.ServiceTestDefaultReport>; ( mount: string, options: { reporter: 'suite'; idiomatic?: false; filter?: string } ): Promise<services.ServiceTestSuiteReport>; ( mount: string, options: { reporter: 'stream'; idiomatic?: false; filter?: string } ): Promise<services.ServiceTestStreamReport>; ( mount: string, options: { reporter: 'tap'; idiomatic?: false; filter?: string } ): Promise<services.ServiceTestTapReport>; ( mount: string, options: { reporter: 'xunit'; idiomatic?: false; filter?: string } ): Promise<services.ServiceTestXunitReport>; ( mount: string, options: { reporter: 'stream'; idiomatic: true; filter?: string } ): Promise<string>; ( mount: string, options: { reporter: 'tap'; idiomatic: true; filter?: string } ): Promise<string>; ( mount: string, options: { reporter: 'xunit'; idiomatic: true; filter?: string } ): Promise<string>;};
Runs the tests of a given service and returns the results using the "default" reporter.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const testReport = await db.runServiceTests("/my-foxx");Runs the tests of a given service and returns the results using the "suite" reporter, which groups the test result by test suite.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const suiteReport = await db.runServiceTests("/my-foxx",{ reporter: "suite" });Runs the tests of a given service and returns the results using the "stream" reporter, which represents the results as a sequence of tuples representing events.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const streamEvents = await db.runServiceTests("/my-foxx",{ reporter: "stream" });Runs the tests of a given service and returns the results using the "tap" reporter, which represents the results as an array of strings using the "tap" format.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const tapLines = await db.runServiceTests("/my-foxx",{ reporter: "tap" });Runs the tests of a given service and returns the results using the "xunit" reporter, which represents the results as an XML document using the JSONML exchange format.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const jsonML = await db.runServiceTests("/my-foxx",{ reporter: "xunit" });Runs the tests of a given service and returns the results as a string using the "stream" reporter in "idiomatic" mode, which represents the results as a line-delimited JSON stream of tuples representing events.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const streamReport = await db.runServiceTests("/my-foxx",{ reporter: "stream", idiomatic: true });Runs the tests of a given service and returns the results as a string using the "tap" reporter in "idiomatic" mode, which represents the results using the "tap" format.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const tapReport = await db.runServiceTests("/my-foxx",{ reporter: "tap", idiomatic: true });Runs the tests of a given service and returns the results as a string using the "xunit" reporter in "idiomatic" mode, which represents the results as an XML document.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for running the tests.
Example 1
const db = new Database();const xml = await db.runServiceTests("/my-foxx",{ reporter: "xunit", idiomatic: true });
method setLicense
setLicense: (license: string, force?: boolean) => Promise<void>;
Set a new license for an Enterprise Edition server.
Parameter license
The license as a base 64 encoded string.
Parameter force
If set to
true
, the license will be changed even if it expires sooner than the current license.
method setLogLevel
setLogLevel: ( levels: Record<string, logs.LogLevelSetting>) => Promise<Record<string, logs.LogLevelSetting>>;
Sets the server's log level for each of the given topics to the given level.
Any omitted topics will be left unchanged.
Parameter levels
An object mapping topic names to log levels.
Example 1
await db.setLogLevel({ request: "debug" });// Debug information will now be logged for each request
method setQueryCacheProperties
setQueryCacheProperties: ( properties: queries.QueryCachePropertiesOptions) => Promise<queries.QueryCacheProperties>;
Updates the global properties for the AQL query results cache.
Parameter properties
The new properties for the AQL query results cache.
Example 1
const db = new Database();await db.setQueryCacheProperties({ maxResults: 9000 });
method setResponseQueueTimeSamples
setResponseQueueTimeSamples: (responseQueueTimeSamples: number) => void;
Sets the limit for the number of values of the most recently received server-reported queue times that can be accessed using Database#queueTime.
Parameter responseQueueTimeSamples
Number of values to maintain.
method setServiceDevelopmentMode
setServiceDevelopmentMode: ( mount: string, enabled?: boolean) => Promise<services.ServiceDescription>;
Enables or disables development mode for the given service.
Parameter mount
The service's mount point, relative to the database.
Parameter enabled
Whether development mode should be enabled or disabled.
Example 1
const db = new Database();await db.setServiceDevelopmentMode("/my-service", true);// the service is now in development modeawait db.setServiceDevelopmentMode("/my-service", false);// the service is now in production mode
method setUserAccessLevel
setUserAccessLevel: ( username: string, options: users.UserAccessLevelOptions, grant: users.AccessLevel) => Promise<connection.ArangoApiResponse<Record<string, users.AccessLevel>>>;
Sets the given ArangoDB user's access level for the database, or the given collection in the given database.
Parameter username
Name of the ArangoDB user to set the access level for.
Parameter options
Database and/or collection to set the access level for.
Parameter grant
Access level to set for the given user.
Example 1
const db = new Database();await db.setUserAccessLevel("steve", { grant: "rw" });// The user "steve" now has read-write access to the current database.Example 2
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 3
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 4
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 5
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 6
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".
method shutdown
shutdown: () => Promise<void>;
Attempts to initiate a clean shutdown of the server.
method status
status: () => Promise<administration.ServerStatusInfo>;
Fetches information about the server status.
Example 1
const status = await db.status();// the status object contains the ArangoDB status information, e.g.// version: ArangoDB version number// host: host identifier of the server// serverInfo: detailed information about the server
method supportInfo
supportInfo: () => Promise< administration.SingleServerSupportInfo | administration.ClusterSupportInfo>;
Fetches deployment information about the server for support purposes.
Note that this API may reveal sensitive data about the deployment.
method time
time: () => Promise<number>;
Retrives the server's current system time in milliseconds with microsecond precision.
method transaction
transaction: (transactionId: string) => transactions.Transaction;
Returns a transactions.Transaction instance for an existing streaming transaction with the given
id
.See also Database#beginTransaction.
Parameter transactionId
The
id
of an existing stream transaction.Example 1
const trx1 = await db.beginTransaction(collections);const id = trx1.id;// laterconst trx2 = db.transaction(id);await trx2.commit();
method transactions
transactions: () => Promise<transactions.Transaction[]>;
Fetches all active transactions from the database and returns an array of transactions.Transaction instances for those transactions.
See also Database#listTransactions.
Example 1
const db = new Database();const transactions = await db.transactions();// transactions is an array of transactions
method uninstallService
uninstallService: ( mount: string, options?: services.UninstallServiceOptions) => Promise<void>;
Completely removes a service from the database.
Parameter mount
The service's mount point, relative to the database.
Parameter options
Options for uninstalling the service.
Example 1
const db = new Database();await db.uninstallService("/my-foxx");
method updateServiceConfiguration
updateServiceConfiguration: { (mount: string, cfg: Record<string, any>, minimal?: false): Promise< Record<string, services.ServiceConfiguration & { warning?: string }> >; (mount: string, cfg: Record<string, any>, minimal: true): Promise<{ values: Record<string, any>; warnings: Record<string, string>; }>;};
Updates the configuration of the given service while maintaining any existing values for options not specified.
See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.
Parameter mount
The service's mount point, relative to the database.
Parameter cfg
An object mapping configuration option names to values.
Parameter minimal
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.Example 1
const db = new Database();const config = { currency: "USD", locale: "en-US" };const info = await db.updateServiceConfiguration("/my-service", config);for (const [key, option] of Object.entries(info)) {console.log(`${option.title} (${key}): ${option.value}`);if (option.warning) console.warn(`Warning: ${option.warning}`);}Updates the configuration of the given service while maintaining any existing values for options not specified.
See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.
Parameter mount
The service's mount point, relative to the database.
Parameter cfg
An object mapping configuration option names to values.
Parameter minimal
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.Example 1
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]}`);}
method updateServiceDependencies
updateServiceDependencies: { (mount: string, deps: Record<string, string>, minimal?: false): Promise< Record< string, ( | services.SingleServiceDependency | services.MultiServiceDependency ) & { warning?: string } > >; (mount: string, deps: Record<string, string>, minimal: true): Promise<{ values: Record<string, string>; warnings: Record<string, 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.
Parameter mount
The service's mount point, relative to the database.
Parameter deps
An object mapping dependency aliases to mount points.
Parameter minimal
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.Example 1
const db = new Database();const deps = { mailer: "/mailer-api", auth: "/remote-auth" };const info = await db.updateServiceDependencies("/my-service", deps);for (const [key, dep] of Object.entries(info)) {console.log(`${dep.title} (${key}): ${dep.current}`);if (dep.warning) console.warn(`Warning: ${dep.warning}`);}Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.
See also Database#replaceServiceDependencies and Database#getServiceDependencies.
Parameter mount
The service's mount point, relative to the database.
Parameter deps
An object mapping dependency aliases to mount points.
Parameter minimal
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.Example 1
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]}`);}
method updateUser
updateUser: { (username: string, passwd: string): Promise< connection.ArangoApiResponse<users.ArangoUser> >; (username: string, options: Partial<users.UserOptions>): Promise< connection.ArangoApiResponse<users.ArangoUser> >;};
Sets the password of a given ArangoDB user to the new value.
Parameter username
Name of the ArangoDB user to change the password for.
Parameter passwd
New password for the ArangoDB user.
Example 1
const db = new Database();const user = await db.updateUser("steve", "hunter2");// The user "steve" has received a new passwordUpdates the ArangoDB user with the new options.
Parameter username
Name of the ArangoDB user to modify.
Parameter options
Options of the ArangoDB user to modify.
Example 1
const db = new Database();const user = await db.updateUser("steve", { active: false });// The user "steve" has been set to inactive
method upgradeService
upgradeService: ( mount: string, source: Blob | string, options?: services.UpgradeServiceOptions) => Promise<services.ServiceDescription>;
Replaces an existing service with a new service while retaining the old service's configuration and dependencies.
Parameter mount
The service's mount point, relative to the database.
Parameter source
The service bundle to install.
Parameter options
Options for upgrading the service.
Example 1
const db = new Database();// Using a Buffer in Node.js as sourceconst source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);const info = await db.upgradeService("/hello", source);Example 2
const db = new Database();// Using a Blob in Node.js as sourceconst source = await fs.openAsBlob("./my-foxx-service.zip");const info = await db.upgradeService("/hello", source);Example 3
const db = new Database();// Using a File from a browser file input as sourceconst element = document.getElementById("my-file-input");const source = element.files[0];const info = await db.upgradeService("/hello", source);
method useBasicAuth
useBasicAuth: (username?: string, password?: string) => this;
Updates the underlying connection's
authorization
header to use Basic authentication with the givenusername
andpassword
, then returns itself.Parameter username
The username to authenticate with.
Parameter password
The password to authenticate with.
Example 1
const db = new Database();db.useBasicAuth("admin", "hunter2");// with the username "admin" and password "hunter2".
method useBearerAuth
useBearerAuth: (token: string) => this;
Updates the underlying connection's
authorization
header to use Bearer authentication with the given authenticationtoken
, then returns itself.Parameter token
The token to authenticate with.
Example 1
const db = new Database();db.useBearerAuth("keyboardcat");// The database instance now uses Bearer authentication.
method userDatabases
userDatabases: () => Promise<Database[]>;
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 1
const db = new Database();const names = await db.userDatabases();// databases is an array of databases
method version
version: (details?: boolean) => Promise<administration.VersionInfo>;
Fetches version information from the ArangoDB server.
Parameter details
If set to
true
, additional information about the ArangoDB server will be available as thedetails
property.Example 1
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
method view
view: (viewName: string) => views.View;
Returns a views.View instance for the given
viewName
.Parameter viewName
Name of the ArangoSearch or SearchAlias View.
Example 1
const db = new Database();const view = db.view("potatoes");
method views
views: () => Promise<views.View[]>;
Fetches all Views from the database and returns an array of views.View instances for the Views.
See also Database#listViews.
Example 1
const db = new Database();const views = await db.views();// views is an array of ArangoSearch View instances
method waitForPropagation
waitForPropagation: ( request: connection.RequestOptions, timeout?: number) => Promise<void>;
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.
Parameter request
Request to perform against each known coordinator.
Parameter timeout
Maximum number of milliseconds to wait for propagation.
Example 1
const db = new Database({ loadBalancingStrategy: "ROUND_ROBIN" });await system.acquireHostList();const analyzer = db.analyzer("my-analyzer");await analyzer.create();await db.waitForPropagation({ pathname: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },30000);// Analyzer has been propagated to all coordinators and can safely be used
method withTransaction
withTransaction: { <T>( collections: transactions.TransactionCollectionOptions, callback: (step: transactions.Transaction['step']) => Promise<T>, options?: transactions.TransactionOptions ): Promise<T>; <T>( collections: (string | collections.ArangoCollection)[], callback: ( step: <T>(callback: () => Promise<T>) => Promise<T> ) => Promise<T>, options?: transactions.TransactionOptions ): Promise<T>; <T>( collection: string | collections.ArangoCollection, callback: ( step: <T>(callback: () => Promise<T>) => Promise<T> ) => Promise<T>, options?: transactions.TransactionOptions ): Promise<T>;};
Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.
Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.Parameter collections
Collections involved in the transaction.
Parameter callback
Callback function executing the transaction steps.
Parameter options
Options for the transaction.
Example 1
const vertices = db.collection("vertices");const edges = db.collection("edges");await db.withTransaction({read: ["vertices"],write: [edges] // collection instances can be passed directly},async (step) => {const start = await step(() => vertices.document("a"));const end = await step(() => vertices.document("b"));await step(() => edges.save({ _from: start._id, _to: end._id }));});Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.
Collections can be specified as collection names (strings) or objects implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.Parameter collections
Collections that can be read from and written to during the transaction.
Parameter callback
Callback function executing the transaction steps.
Parameter options
Options for the transaction.
Example 1
const vertices = db.collection("vertices");const edges = db.collection("edges");await db.withTransaction(["vertices",edges, // collection instances can be passed directly],async (step) => {const start = await step(() => vertices.document("a"));const end = await step(() => vertices.document("b"));await step(() => edges.save({ _from: start._id, _to: end._id }));});Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.
The Collection can be specified as a collection name (string) or an object implementing the collections.ArangoCollection interface:
Collection
, graphs.GraphVertexCollection, graphs.GraphEdgeCollection as well as (in TypeScript) collections.DocumentCollection and collections.EdgeCollection.Parameter collection
A collection that can be read from and written to during the transaction.
Parameter callback
Callback function executing the transaction steps.
Parameter options
Options for the transaction.
Example 1
const vertices = db.collection("vertices");const start = vertices.document("a");const end = vertices.document("b");const edges = db.collection("edges");await db.withTransaction(edges, // collection instances can be passed directlyasync (step) => {await step(() => edges.save({ _from: start._id, _to: end._id }));});
Package Files (3)
Dependencies (1)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/arangojs
.
- Markdown[](https://www.jsdocs.io/package/arangojs)
- HTML<a href="https://www.jsdocs.io/package/arangojs"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 7265 ms. - Missing or incorrect documentation? Open an issue for this package.