Creates a new Database
instance with its own connection pool.
See also database.
const db = new Database({
url: "http://127.0.0.1:8529",
databaseName: "my_database",
auth: { username: "admin", password: "hunter2" },
});
Optional
config: ConfigAn object with configuration options.
Creates a new Database
instance with its own connection pool.
See also database.
const db = new Database("http://127.0.0.1:8529", "my_database");
db.useBasicAuth("admin", "hunter2");
Base URL of the ArangoDB server or list of server URLs.
Equivalent to the url
option in Config.
Optional
name: stringName of the ArangoDB database this instance represents.
Methods for accessing the server-reported queue times of the mostly recently received responses.
Updates the URL list by requesting a list of all coordinators in the cluster and adding any endpoints not initially specified in the Config.
For long-running processes communicating with an ArangoDB cluster it is recommended to run this method periodically (e.g. once per hour) to make sure new coordinators are picked up correctly and can be used for fail-over or load balancing.
const db = new Database();
const interval = setInterval(
() => db.acquireHostList(),
5 * 60 * 1000 // every 5 minutes
);
// later
clearInterval(interval);
system.close();
If set to true
, the existing host list will be
replaced instead of extended.
Fetches all Analyzers visible in the database and returns an array of Analyzer instances for those Analyzers.
See also listAnalyzers.
const db = new Database();
const analyzers = await db.analyzers();
// analyzers is an array of Analyzer instances
Begins a new streaming transaction for the given collections, then returns a Transaction instance for the transaction.
Collections can be specified as collection names (strings) or objects
implementing the ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as
well as (in TypeScript) DocumentCollection and
EdgeCollection.
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();
Collections involved in the transaction.
Optional
options: TransactionOptionsOptions for the transaction.
Begins a new streaming transaction for the given collections, then returns a Transaction instance for the transaction.
Collections can be specified as collection names (strings) or objects
implementing the ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
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();
Collections that can be read from and written to during the transaction.
Optional
options: TransactionOptionsOptions for the transaction.
Begins a new streaming transaction for the given collections, then returns a Transaction instance for the transaction.
The Collection can be specified as a collection name (string) or an object
implementing the ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
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();
A collection that can be read from and written to during the transaction.
Optional
options: TransactionOptionsOptions for the transaction.
Clears the list of recent slow queries.
See also listSlowQueries.
const db = new Database();
await db.clearSlowQueries();
// Slow query list is now cleared
Clears the given ArangoDB user's access level for the database, or the given collection in the given database.
const db = new Database();
await db.clearUserAccessLevel("steve");
// The access level of the user "steve" has been cleared for the current
// database.
const db = new Database();
await db.clearUserAccessLevel("steve", { database: "staging" });
// The access level of the user "steve" has been cleared for the "staging"
// database.
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.
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.
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.
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".
Name of the ArangoDB user to clear the access level for.
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.
const db = new Database();
const sessions = db.collection("sessions");
// Clean up expired sessions once per hour
setInterval(async () => {
await db.query(aql`
FOR session IN ${sessions}
FILTER session.expires < DATE_NOW()
REMOVE session IN ${sessions}
`);
// Making sure to close the connections because they're no longer used
system.close();
}, 1000 * 60 * 60);
Returns a Collection
instance for the given collection name.
In TypeScript the collection implements both the DocumentCollection and EdgeCollection interfaces and can be cast to either type to enforce a stricter API.
const db = new Database();
const collection = db.collection("potatoes");
interface Person {
name: string;
}
const db = new Database();
const persons = db.collection<Person>("persons");
interface Person {
name: string;
}
interface Friend {
startDate: number;
endDate?: number;
}
const db = new Database();
const documents = db.collection("persons") as DocumentCollection<Person>;
const edges = db.collection("friends") as EdgeCollection<Friend>;
Type to use for document data. Defaults to any
.
Name of the edge collection.
Fetches all collections from the database and returns an array of
Collection
instances.
In TypeScript these instances implement both the DocumentCollection and EdgeCollection interfaces and can be cast to either type to enforce a stricter API.
See also listCollections.
const db = new Database();
const collections = await db.collections();
// collections is an array of DocumentCollection and EdgeCollection
// instances not including system collections
const db = new Database();
const collections = await db.collections(false);
// collections is an array of DocumentCollection and EdgeCollection
// instances including system collections
Whether system collections should be excluded.
Writes all locally available services to the database and updates any service bundles missing in the database.
await db.commitLocalServiceState();
// all services available on the coordinator have been written to the db
await db.commitLocalServiceState(true);
// all service conflicts have been resolved in favor of this coordinator
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.
Computes a set of move shard operations to rebalance the cluster.
const db = new Database();
const result = await db.computerClusterRebalance({
moveLeaders: true,
moveFollowers: true
});
if (result.moves.length) {
await db.executeClusterRebalance(result.moves);
}
Creates a new Analyzer with the given analyzerName
and options
, then
returns an Analyzer instance for the new Analyzer.
const db = new Database();
const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });
// the identity Analyzer "potatoes" now exists
Name of the Analyzer.
An object defining the properties of the Analyzer.
Creates a new collection with the given collectionName
and options
,
then returns a DocumentCollection instance for the new collection.
const db = new Database();
const documents = db.createCollection("persons");
interface Person {
name: string;
}
const db = new Database();
const documents = db.createCollection<Person>("persons");
Type to use for document data. Defaults to any
.
Name of the new collection.
Optional
options: CreateCollectionOptions & { Options for creating the collection.
Creates a new edge collection with the given collectionName
and
options
, then returns an EdgeCollection instance for the new
edge collection.
const db = new Database();
const edges = db.createCollection("friends", {
type: CollectionType.EDGE_COLLECTION
});
interface Friend {
startDate: number;
endDate?: number;
}
const db = new Database();
const edges = db.createCollection<Friend>("friends", {
type: CollectionType.EDGE_COLLECTION
});
Type to use for edge document data. Defaults to any
.
Name of the new collection.
Options for creating the collection.
Creates a new database with the given databaseName
with the given
options
and returns a Database
instance for that database.
const db = new Database();
const info = await db.createDatabase("mydb", {
users: [{ username: "root" }]
});
// the database has been created
Name of the database to create.
Optional
options: CreateDatabaseOptionsOptions for creating the database.
Creates a new database with the given databaseName
with the given
users
and returns a Database
instance for that database.
const db = new Database();
const info = await db.createDatabase("mydb", [{ username: "root" }]);
// the database has been created
Name of the database to create.
Database users to create with the database.
Creates a new edge collection with the given collectionName
and
options
, then returns an EdgeCollection instance for the new
edge collection.
This is a convenience method for calling createCollection
with options.type
set to EDGE_COLLECTION
.
const db = new Database();
const edges = db.createEdgeCollection("friends");
interface Friend {
startDate: number;
endDate?: number;
}
const db = new Database();
const edges = db.createEdgeCollection<Friend>("friends");
Type to use for edge document data. Defaults to any
.
Name of the new collection.
Optional
options: CreateCollectionOptionsOptions for creating the collection.
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.
const db = new Database();
await db.createFunction(
"ACME::ACCOUNTING::CALCULATE_VAT",
"(price) => price * 0.19"
);
// Use the new function in an AQL query with template handler:
const cursor = await db.query(aql`
FOR product IN products
RETURN MERGE(
{ vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price) },
product
)
`);
// cursor is a cursor for the query result
A valid AQL function name. The function name must consist of at least two alphanumeric identifiers separated with double colons.
A string evaluating to a JavaScript function (not a JavaScript function object).
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.
Creates a graph with the given graphName
and edgeDefinitions
, then
returns a Graph instance for the new graph.
Name of the graph to be created.
An array of edge definitions.
Optional
options: CreateGraphOptionsAn object defining the properties of the graph.
(Enterprise Edition only.) Creates a hot backup of the entire ArangoDB deployment including all databases, collections, etc.
Returns an object describing the backup result.
const info = await db.createHotBackup();
// a hot backup has been created
Options for creating the backup.
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 Job instance that can be used to retrieve the result of the callback function once the request has been executed.
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
Callback function to execute as an async job.
Creates a new ArangoDB user with the given password.
const db = new Database();
const user = await db.createUser("steve", "hunter2");
// The user "steve" has been created
Name of the ArangoDB user to create.
Password of the new ArangoDB user.
Creates a new ArangoDB user with the given options.
const db = new Database();
const user = await db.createUser("steve", { passwd: "hunter2" });
// The user "steve" has been created
Name of the ArangoDB user to create.
Additional options for creating the ArangoDB user.
Creates a new View with the given viewName
and options
, then returns a
View instance for the new View.
const db = new Database();
const view = await db.createView("potatoes", { type: "arangosearch" });
// the ArangoSearch View "potatoes" now exists
Name of the View.
An object defining the properties of the View.
Creates a new Database
instance for the given databaseName
that
shares this database's connection pool.
See also new Database.
const systemDb = new Database();
const myDb = system.database("my_database");
Name of the database.
Fetches all databases from the server and returns an array of Database
instances for those databases.
See also listDatabases and userDatabases.
const db = new Database();
const names = await db.databases();
// databases is an array of databases
Deletes the results of all completed async jobs created before the given threshold.
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
The expiration timestamp in milliseconds.
Retrieves a zip bundle containing the service files.
Returns a Buffer
in node.js or Blob
in the browser.
const db = new Database();
const serviceBundle = await db.downloadService("/my-foxx");
The service's mount point, relative to the database.
Deletes the database with the given databaseName
from the server.
const db = new Database();
await db.dropDatabase("mydb");
// database "mydb" no longer exists
Name of the database to delete.
Deletes the AQL user function with the given name from the database.
const db = new Database();
await db.dropFunction("ACME::ACCOUNTING::CALCULATE_VAT");
// the function no longer exists
The name of the user function to drop.
If set to true
, all functions with a name starting with
name
will be deleted, otherwise only the function with the exact name
will be deleted.
Executes the given cluster move shard operations.
const db = new Database();
const result = await db.computerClusterRebalance({
moveLeaders: true,
moveFollowers: true
});
if (result.moves.length) {
await db.executeClusterRebalance(result.moves);
}
Performs a server-side JavaScript transaction and returns its return value.
Collections can be specified as collection names (strings) or objects
implementing the ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
Note: The action
function will be evaluated and executed on the
server inside ArangoDB's embedded JavaScript environment and can not
access any values other than those passed via the params
option.
See the official ArangoDB documentation for
the JavaScript @arangodb
module
for information about accessing the database from within ArangoDB's
server-side JavaScript environment.
const db = new Database();
const action = `
function(params) {
// This code will be executed inside ArangoDB!
const { query } = require("@arangodb");
return query\`
FOR user IN _users
FILTER user.age > ${params.age}
RETURN u.user
\`.toArray();
}
`);
const result = await db.executeTransaction({
read: ["_users"]
}, action, {
params: { age: 12 }
});
// result contains the return value of the action
Collections involved in the transaction.
A string evaluating to a JavaScript function to be executed on the server.
Optional
options: TransactionOptions & { Options for the transaction. If options.allowImplicit
is specified, it will be used if collections.allowImplicit
was not
specified.
Performs a server-side transaction and returns its return value.
Collections can be specified as collection names (strings) or objects
implementing the ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
Note: The action
function will be evaluated and executed on the
server inside ArangoDB's embedded JavaScript environment and can not
access any values other than those passed via the params
option.
See the official ArangoDB documentation for
the JavaScript @arangodb
module
for information about accessing the database from within ArangoDB's
server-side JavaScript environment.
const db = new Database();
const action = `
function(params) {
// This code will be executed inside ArangoDB!
const { query } = require("@arangodb");
return query\`
FOR user IN _users
FILTER user.age > ${params.age}
RETURN u.user
\`.toArray();
}
`);
const result = await db.executeTransaction(["_users"], action, {
params: { age: 12 }
});
// result contains the return value of the action
Collections that can be read from and written to during the transaction.
A string evaluating to a JavaScript function to be executed on the server.
Optional
options: TransactionOptions & { Options for the transaction.
Performs a server-side transaction and returns its return value.
The Collection can be specified as a collection name (string) or an object
implementing the ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
Note: The action
function will be evaluated and executed on the
server inside ArangoDB's embedded JavaScript environment and can not
access any values other than those passed via the params
option.
See the official ArangoDB documentation for
the JavaScript @arangodb
module
for information about accessing the database from within ArangoDB's
server-side JavaScript environment.
const db = new Database();
const action = `
function(params) {
// This code will be executed inside ArangoDB!
const { query } = require("@arangodb");
return query\`
FOR user IN _users
FILTER user.age > ${params.age}
RETURN u.user
\`.toArray();
}
`);
const result = await db.executeTransaction("_users", action, {
params: { age: 12 }
});
// result contains the return value of the action
A collection that can be read from and written to during the transaction.
A string evaluating to a JavaScript function to be executed on the server.
Optional
options: TransactionOptions & { Options for the transaction.
Explains a database query using the given query
.
See the aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
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
`);
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql template string.
Optional
options: ExplainOptions & { Options for explaining the query.
Explains a database query using the given query
.
See the aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
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 }
);
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql template string.
Optional
options: ExplainOptions & { Options for explaining the query.
Explains a database query using the given query
and bindVars
.
See the aql template string handler for a safer and easier alternative to passing strings directly.
const db = new Database();
const collection = db.collection("some-collection");
const explanation = await db.explain(
`
FOR doc IN @@collection
FILTER doc.flavor == "strawberry"
RETURN doc._key
`,
{ "@collection": collection.name }
);
An AQL query string.
Optional
bindVars: Record<string, any>An object defining bind parameters for the query.
Optional
options: ExplainOptions & { Options for explaining the query.
Explains a database query using the given query
and bindVars
.
See the aql template string handler for a safer and easier alternative to passing strings directly.
const db = new Database();
const collection = db.collection("some-collection");
const explanation = await db.explain(
`
FOR doc IN @@collection
FILTER doc.flavor == "strawberry"
RETURN doc._key
`,
{ "@collection": collection.name },
{ allPlans: true }
);
An AQL query string.
Optional
bindVars: Record<string, any>An object defining bind parameters for the query.
Optional
options: ExplainOptions & { Options for explaining the query.
Fetches the database description for the active database from the server.
const db = new Database();
const info = await db.get();
// the database exists
Computes the current cluster imbalance.
const db = new Database();
const imbalance = await db.getClusterImbalance();
Retrieves the log messages from the server's global log.
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]})`);
}
Optional
options: LogEntriesOptionsOptions for retrieving the log entries.
Retrieves the server's current log level for each topic.
const levels = await db.getLogLevel();
console.log(levels.request); // log level for incoming requests
Retrieves the log messages from the server's global log.
This endpoint has been deprecated in ArangoDB 3.8. Use getLogEntries instead.
const messages = await db.getLogMessages();
for (const m of messages) {
console.log(`${m.date} - [${m.level}] ${m.message} (#${m.id})`);
}
Optional
options: LogEntriesOptionsOptions for retrieving the log entries.
Retrieves information about a mounted service.
const db = new Database();
const info = await db.getService("/my-service");
// info contains detailed information about the service
The service's mount point, relative to the database.
Retrieves information about the service's configuration options and their current values.
See also replaceServiceConfiguration and updateServiceConfiguration.
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}`);
}
The service's mount point, relative to the database.
Optional
minimal: falseIf set to true
, the result will only include each
configuration option's current value. Otherwise it will include the full
definition for each option.
Retrieves information about the service's configuration options and their current values.
See also replaceServiceConfiguration and updateServiceConfiguration.
const db = new Database();
const config = await db.getServiceConfiguration("/my-service", true);
for (const [key, value] of Object.entries(config)) {
console.log(`${key}: ${value}`);
}
The service's mount point, relative to the database.
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.
Retrieves information about the service's dependencies and their current mount points.
See also replaceServiceDependencies and updateServiceDependencies.
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}`);
}
The service's mount point, relative to the database.
Optional
minimal: falseIf set to true
, the result will only include each
dependency's current mount point. Otherwise it will include the full
definition for each dependency.
Retrieves information about the service's dependencies and their current mount points.
See also replaceServiceDependencies and updateServiceDependencies.
const db = new Database();
const deps = await db.getServiceDependencies("/my-service", true);
for (const [key, value] of Object.entries(deps)) {
console.log(`${key}: ${value}`);
}
The service's mount point, relative to the database.
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.
Retrieves an Open API compatible Swagger API description object for the service installed at the given mount point.
const db = new Database();
const spec = await db.getServiceDocumentation("/my-service");
// spec is a Swagger API description of the service
The service's mount point, relative to the database.
Retrieves the text content of the service's README
or README.md
file.
Returns undefined
if no such file could be found.
const db = new Database();
const readme = await db.getServiceReadme("/my-service");
if (readme !== undefined) console.log(readme);
else console.warn(`No README found.`)
The service's mount point, relative to the database.
Fetches the user data of a single ArangoDB user.
const db = new Database();
const user = await db.getUser("steve");
// user is the user object for the user named "steve"
Name of the ArangoDB user to fetch.
Fetches the given ArangoDB user's access level for the database, or the given collection in the given database.
const db = new Database();
const accessLevel = await db.getUserAccessLevel("steve");
// The access level of the user "steve" has been fetched for the current
// database.
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.
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.
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.
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.
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".
Name of the ArangoDB user to fetch the access level for.
Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases.
const db = new Database();
const accessLevels = await db.getUserDatabases("steve");
for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {
console.log(`${databaseName}: ${accessLevel}`);
}
Name of the ArangoDB user to fetch the access levels for.
Optional
full: falseWhether access levels for collections should be included.
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.
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}`);
}
}
Name of the ArangoDB user to fetch the access levels for.
Whether access levels for collections should be included.
Fetches all graphs from the database and returns an array of Graph instances for those graphs.
See also listGraphs.
const db = new Database();
const graphs = await db.graphs();
// graphs is an array of Graph instances
Installs a new service.
const db = new Database();
// Using a node.js file stream as source
const source = fs.createReadStream("./my-foxx-service.zip");
const info = await db.installService("/hello", source);
const db = new Database();
// Using a node.js Buffer as source
const source = fs.readFileSync("./my-foxx-service.zip");
const info = await db.installService("/hello", source);
const db = new Database();
// Using a File (Blob) from a browser file input
const element = document.getElementById("my-file-input");
const source = element.files[0];
const info = await db.installService("/hello", source);
The service's mount point, relative to the database.
The service bundle to install.
Options for installing the service.
Kills a running query with the given queryId
.
See also listRunningQueries.
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);
}
}
));
The ID of a currently running query.
Fetches all Analyzers visible in the database and returns an array of Analyzer descriptions.
See also analyzers.
const db = new Database();
const analyzers = await db.listAnalyzers();
// analyzers is an array of Analyzer descriptions
Fetches all collections from the database and returns an array of collection descriptions.
See also collections.
const db = new Database();
const collections = await db.listCollections();
// collections is an array of collection descriptions
// not including system collections
const db = new Database();
const collections = await db.listCollections(false);
// collections is an array of collection descriptions
// including system collections
Whether system collections should be excluded.
Fetches all databases from the server and returns an array of their names.
See also databases and listUserDatabases.
const db = new Database();
const names = await db.listDatabases();
// databases is an array of database names
Fetches a list of all AQL user functions registered with the database.
const db = new Database();
const functions = await db.listFunctions();
const names = functions.map(fn => fn.name);
(Enterprise Edition only.) Retrieves a list of all locally found hot backups.
const backups = await db.listHotBackups();
for (const backup of backups) {
console.log(backup.id);
}
Optional
id: string | string[]If specified, only the backup with the given ID will be returned.
Fetches a list of information for all currently running queries.
See also listSlowQueries and killQuery.
const db = new Database();
const queries = await db.listRunningQueries();
Retrieves a list of scripts defined in the service manifest's "scripts" section mapped to their human readable representations.
const db = new Database();
const scripts = await db.listServiceScripts("/my-service");
for (const [name, title] of Object.entries(scripts)) {
console.log(`${name}: ${title}`);
}
The service's mount point, relative to the database.
Fetches a list of all installed service.
const db = new Database();
const services = await db.listServices();
const db = new Database();
const services = await db.listServices(false); // all services
Whether system services should be excluded.
Fetches a list of information for all recent slow queries.
See also listRunningQueries and clearSlowQueries.
const db = new Database();
const queries = await db.listSlowQueries();
// Only works if slow query tracking is enabled
Fetches all active transactions from the database and returns an array of transaction descriptions.
See also transactions.
const db = new Database();
const transactions = await db.listTransactions();
// transactions is an array of transaction descriptions
Fetches all databases accessible to the active user from the server and returns an array of their names.
See also userDatabases and listDatabases.
const db = new Database();
const names = await db.listUserDatabases();
// databases is an array of database names
Fetches all ArangoDB users visible to the authenticated user and returns an array of user objects.
const db = new Database();
const users = await db.listUsers();
// users is an array of user objects
Fetches all Views from the database and returns an array of View descriptions.
See also views.
const db = new Database();
const views = await db.listViews();
// views is an array of View descriptions
Validates the given database credentials and exchanges them for an authentication token, then uses the authentication token for future requests and returns it.
const db = new Database();
await db.login("admin", "hunter2");
// with an authentication token for the "admin" user.
The username to authenticate with.
The password to authenticate with.
Parses the given query and returns the result.
See the aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
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
`);
An AQL query string or an object containing an AQL query string and bind parameters, e.g. the object returned from an aql template string.
Performs a database query using the given query
, then returns a new
ArrayCursor instance for the result set.
See the aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
Note: When executing a query in a streaming transaction using the
step
method, the resulting cursor will be bound to that transaction and
you do not need to use the step
method to consume it.
const db = new Database();
const active = true;
const Users = db.collection("_users");
// Using an aql template string:
// Bind parameters are automatically extracted and arangojs collections
// are automatically passed as collection bind parameters.
const cursor = await db.query(aql`
FOR u IN ${Users}
FILTER u.authData.active == ${active}
RETURN u.user
`);
// cursor is a cursor for the query result
const db = new Database();
const active = true;
const Users = db.collection("_users");
// Using an object with a regular multi-line string
const cursor = await db.query({
query: `
FOR u IN @@users
FILTER u.authData.active == @active
RETURN u.user
`,
bindVars: { active: active, "@users": Users.name }
});
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql template string.
Optional
options: QueryOptionsOptions for the query execution.
Performs a database query using the given query
and bindVars
, then
returns a new ArrayCursor instance for the result set.
See the aql template string handler for a safer and easier alternative to passing strings directly.
Note: When executing a query in a streaming transaction using the
step
method, the resulting cursor will be bound to that transaction and
you do not need to use the step
method to consume it.
const db = new Database();
const active = true;
const Users = db.collection("_users");
const cursor = await db.query(
// A normal multi-line string
`
FOR u IN @@users
FILTER u.authData.active == @active
RETURN u.user
`,
{ active: active, "@users": Users.name }
);
const db = new Database();
const active = true;
const Users = db.collection("_users");
const cursor = await db.query(
// An AQL literal created from a normal multi-line string
aql.literal(`
FOR u IN @@users
FILTER u.authData.active == @active
RETURN u.user
`),
{ active: active, "@users": Users.name }
);
An AQL query string.
Optional
bindVars: Record<string, any>An object defining bind parameters for the query.
Optional
options: QueryOptionsOptions for the query execution.
Fetches the available optimizer rules.
const db = new Database();
const rules = await db.queryRules();
for (const rule of rules) {
console.log(rule.name);
}
Fetches the query tracking properties.
const db = new Database();
const tracking = await db.queryTracking();
console.log(tracking.enabled);
Modifies the query tracking properties.
const db = new Database();
// track up to 5 slow queries exceeding 5 seconds execution time
await db.setQueryTracking({
enabled: true,
trackSlowQueries: true,
maxSlowQueries: 5,
slowQueryThreshold: 5
});
Options for query tracking.
Computes a set of move shard operations to rebalance the cluster and executes them.
const db = new Database();
const result = await db.rebalanceCluster({
moveLeaders: true,
moveFollowers: true
});
// The cluster is now rebalanced.
Removes the ArangoDB user with the given username from the server.
const db = new Database();
await db.removeUser("steve");
// The user "steve" has been removed
Name of the ArangoDB user to remove.
Renames the collection collectionName
to newName
.
Additionally removes any stored Collection
instance for
collectionName
from the Database
instance's internal cache.
Note: Renaming collections may not be supported when ArangoDB is running in a cluster configuration.
Current name of the collection.
The new name of the collection.
Renames the view viewName
to newName
.
Additionally removes any stored View instance for viewName
from
the Database
instance's internal cache.
Note: Renaming views may not be supported when ArangoDB is running in a cluster configuration.
Current name of the view.
The new name of the view.
Attempts to renew the authentication token passed to useBearerAuth or returned and used by login. If a new authentication token is issued, it will be used for future requests and returned.
const db = new Database();
await db.login("admin", "hunter2");
// ... later ...
const newToken = await db.renewAuthToken();
if (!newToken) // no new token issued
Replaces an existing service with a new service by completely removing the old service and installing a new service at the same mount point.
const db = new Database();
// Using a node.js file stream as source
const source = fs.createReadStream("./my-foxx-service.zip");
const info = await db.replaceService("/hello", source);
const db = new Database();
// Using a node.js Buffer as source
const source = fs.readFileSync("./my-foxx-service.zip");
const info = await db.replaceService("/hello", source);
const db = new Database();
// Using a File (Blob) from a browser file input
const element = document.getElementById("my-file-input");
const source = element.files[0];
const info = await db.replaceService("/hello", source);
The service's mount point, relative to the database.
The service bundle to install.
Options for replacing the service.
Replaces the configuration of the given service, discarding any existing values for options not specified.
See also updateServiceConfiguration and getServiceConfiguration.
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}`);
}
The service's mount point, relative to the database.
An object mapping configuration option names to values.
Optional
minimal: falseIf 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.
Replaces the configuration of the given service, discarding any existing values for options not specified.
See also updateServiceConfiguration and getServiceConfiguration.
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]}`);
}
The service's mount point, relative to the database.
An object mapping configuration option names to values.
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.
Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.
See also updateServiceDependencies and getServiceDependencies.
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}`);
}
The service's mount point, relative to the database.
Optional
minimal: falseIf set to true
, the result will only include each
dependency's current mount point. Otherwise it will include the full
definition for each dependency.
Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.
See also updateServiceDependencies and getServiceDependencies.
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]}`);
}
The service's mount point, relative to the database.
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.
Replaces the ArangoDB user's option with the new options.
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
Name of the ArangoDB user to modify.
New options to replace the user's existing options.
(Enteprise Edition only.) Restores a consistent local hot backup.
Returns the directory path of the restored backup.
await db.restoreHotBackup("2023-09-19T15.38.21Z_example");
// the backup has been restored
The ID of the backup to restore.
Returns a new Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.
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"}'
Optional
path: stringThe database-relative URL of the route. Defaults to the database API root.
Optional
headers: HeadersDefault headers that should be sent with each request to the route.
Executes a service script and retrieves its result exposed as
module.exports
(if any).
const db = new Database();
const result = await db.runServiceScript(
"/my-service",
"create-user",
{
username: "service_admin",
password: "hunter2"
}
);
The service's mount point, relative to the database.
Name of the service script to execute as defined in the service manifest.
Optional
params: anyArbitrary 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.
Runs the tests of a given service and returns the results using the "default" reporter.
const db = new Database();
const testReport = await db.runServiceTests("/my-foxx");
The service's mount point, relative to the database.
Optional
options: { Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Optional
idiomatic?: falseWhether the reporter should use "idiomatic" mode. Has no effect when using the "default" or "suite" reporters.
Optional
reporter?: "default"Runs the tests of a given service and returns the results using the "suite" reporter, which groups the test result by test suite.
const db = new Database();
const suiteReport = await db.runServiceTests(
"/my-foxx",
{ reporter: "suite" }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Optional
idiomatic?: falseWhether the reporter should use "idiomatic" mode. Has no effect when using the "default" or "suite" reporters.
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.
const db = new Database();
const streamEvents = await db.runServiceTests(
"/my-foxx",
{ reporter: "stream" }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Optional
idiomatic?: falseWhether the reporter should use "idiomatic" mode. If set to true
,
the results will be returned as a formatted string.
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.
const db = new Database();
const tapLines = await db.runServiceTests(
"/my-foxx",
{ reporter: "tap" }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Optional
idiomatic?: falseWhether the reporter should use "idiomatic" mode. If set to true
,
the results will be returned as a formatted string.
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.
const db = new Database();
const jsonML = await db.runServiceTests(
"/my-foxx",
{ reporter: "xunit" }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Optional
idiomatic?: falseWhether the reporter should use "idiomatic" mode. If set to true
,
the results will be returned as a formatted string.
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.
const db = new Database();
const streamReport = await db.runServiceTests(
"/my-foxx",
{ reporter: "stream", idiomatic: true }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Whether the reporter should use "idiomatic" mode. If set to false
,
the results will be returned as an array of tuples instead of a
string.
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.
const db = new Database();
const tapReport = await db.runServiceTests(
"/my-foxx",
{ reporter: "tap", idiomatic: true }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Whether the reporter should use "idiomatic" mode. If set to false
,
the results will be returned as an array of strings instead of a
single string.
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.
const db = new Database();
const xml = await db.runServiceTests(
"/my-foxx",
{ reporter: "xunit", idiomatic: true }
);
The service's mount point, relative to the database.
Options for running the tests.
Optional
filter?: stringIf set, only tests with full names including this exact string will be executed.
Whether the reporter should use "idiomatic" mode. If set to false
,
the results will be returned using the JSONML exchange format
instead of a string.
Sets the server's log level for each of the given topics to the given level.
Any omitted topics will be left unchanged.
await db.setLogLevel({ request: "debug" });
// Debug information will now be logged for each request
An object mapping topic names to log levels.
Sets the limit for the number of values of the most recently received server-reported queue times that can be accessed using queueTime.
Number of values to maintain.
Enables or disables development mode for the given service.
const db = new Database();
await db.setServiceDevelopmentMode("/my-service", true);
// the service is now in development mode
await db.setServiceDevelopmentMode("/my-service", false);
// the service is now in production mode
The service's mount point, relative to the database.
Whether development mode should be enabled or disabled.
Sets the given ArangoDB user's access level for the database, or the given collection in the given database.
const db = new Database();
await db.setUserAccessLevel("steve", { grant: "rw" });
// The user "steve" now has read-write access to the current database.
const db = new Database();
await db.setUserAccessLevel("steve", {
database: "staging",
grant: "rw"
});
// The user "steve" now has read-write access to the "staging" database.
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.
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.
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.
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".
Name of the ArangoDB user to set the access level for.
Returns a Transaction instance for an existing streaming
transaction with the given id
.
See also beginTransaction.
const trx1 = await db.beginTransaction(collections);
const id = trx1.id;
// later
const trx2 = db.transaction(id);
await trx2.commit();
Fetches all active transactions from the database and returns an array of Transaction instances for those transactions.
See also listTransactions.
const db = new Database();
const transactions = await db.transactions();
// transactions is an array of transactions
Completely removes a service from the database.
const db = new Database();
await db.uninstallService("/my-foxx");
The service's mount point, relative to the database.
Optional
options: UninstallServiceOptionsOptions for uninstalling the service.
Updates the configuration of the given service while maintaining any existing values for options not specified.
See also replaceServiceConfiguration and getServiceConfiguration.
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}`);
}
The service's mount point, relative to the database.
An object mapping configuration option names to values.
Optional
minimal: falseIf 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.
Updates the configuration of the given service while maintaining any existing values for options not specified.
See also replaceServiceConfiguration and getServiceConfiguration.
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]}`);
}
The service's mount point, relative to the database.
An object mapping configuration option names to values.
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.
Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.
See also replaceServiceDependencies and getServiceDependencies.
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}`);
}
The service's mount point, relative to the database.
Optional
minimal: falseIf set to true
, the result will only include each
dependency's current mount point. Otherwise it will include the full
definition for each dependency.
Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.
See also replaceServiceDependencies and getServiceDependencies.
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]}`);
}
The service's mount point, relative to the database.
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.
Sets the password of a given ArangoDB user to the new value.
const db = new Database();
const user = await db.updateUser("steve", "hunter2");
// The user "steve" has received a new password
Name of the ArangoDB user to change the password for.
New password for the ArangoDB user.
Updates the ArangoDB user with the new options.
const db = new Database();
const user = await db.updateUser("steve", { active: false });
// The user "steve" has been set to inactive
Name of the ArangoDB user to modify.
Options of the ArangoDB user to modify.
Replaces an existing service with a new service while retaining the old service's configuration and dependencies.
const db = new Database();
// Using a node.js file stream as source
const source = fs.createReadStream("./my-foxx-service.zip");
const info = await db.upgradeService("/hello", source);
const db = new Database();
// Using a node.js Buffer as source
const source = fs.readFileSync("./my-foxx-service.zip");
const info = await db.upgradeService("/hello", source);
const db = new Database();
// Using a File (Blob) from a browser file input
const element = document.getElementById("my-file-input");
const source = element.files[0];
const info = await db.upgradeService("/hello", source);
The service's mount point, relative to the database.
The service bundle to install.
Options for upgrading the service.
Updates the underlying connection's authorization
header to use Basic
authentication with the given username
and password
, then returns
itself.
const db = new Database();
db.useBasicAuth("admin", "hunter2");
// with the username "admin" and password "hunter2".
The username to authenticate with.
The password to authenticate with.
Updates the underlying connection's authorization
header to use Bearer
authentication with the given authentication token
, then returns itself.
const db = new Database();
db.useBearerAuth("keyboardcat");
// The database instance now uses Bearer authentication.
The token to authenticate with.
Fetches all databases accessible to the active user from the server and
returns an array of Database
instances for those databases.
See also listUserDatabases and databases.
const db = new Database();
const names = await db.userDatabases();
// databases is an array of databases
Fetches version information from the ArangoDB server.
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
Optional
details: booleanIf set to true
, additional information about the
ArangoDB server will be available as the details
property.
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.
const db = new Database({ loadBalancingStrategy: "ROUND_ROBIN" });
await system.acquireHostList();
const analyzer = db.analyzer("my-analyzer");
await analyzer.create();
await db.waitForPropagation(
{ path: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },
30000
);
// Analyzer has been propagated to all coordinators and can safely be used
Request to perform against each known coordinator.
Optional
timeout: numberMaximum number of milliseconds to wait for propagation.
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 ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as
well as (in TypeScript) DocumentCollection and
EdgeCollection.
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 }));
}
);
Collections involved in the transaction.
Callback function executing the transaction steps.
Executes the given function locally as a single step of the transaction.
const db = new Database();
const vertices = db.collection("vertices");
const edges = db.collection("edges");
const trx = await db.beginTransaction({ write: [vertices, edges] });
// The following code will be part of the transaction
const left = await trx.step(() => vertices.save({ label: "left" }));
const right = await trx.step(() => vertices.save({ label: "right" }));
// Results from preceding actions can be used normally
await trx.step(() => edges.save({
_from: left._id,
_to: right._id,
data: "potato"
}));
// Transaction must be committed for changes to take effected
// Always call either trx.commit or trx.abort to end a transaction
await trx.commit();
// BAD! If the callback is an async function it must only use await once!
await trx.step(async () => {
await collection.save(data);
await collection.save(moreData); // WRONG
});
// BAD! Callback function must use only one arangojs call!
await trx.step(() => {
return collection.save(data)
.then(() => collection.save(moreData)); // WRONG
});
// BETTER: Wrap every arangojs method call that should be part of the
// transaction in a separate `trx.step` call
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
// BAD! If the callback is an async function it must not await before
// calling an arangojs method!
await trx.step(async () => {
await doSomethingElse();
return collection.save(data); // WRONG
});
// BAD! Any arangojs inside the callback must not happen inside a promise
// method!
await trx.step(() => {
return doSomethingElse()
.then(() => collection.save(data)); // WRONG
});
// BETTER: Perform any async logic needed outside the `trx.step` call
await doSomethingElse();
await trx.step(() => collection.save(data));
// OKAY: You can perform async logic in the callback after the arangojs
// method call as long as it does not involve additional arangojs method
// calls, but this makes it easy to make mistakes later
await trx.step(async () => {
await collection.save(data);
await doSomethingDifferent(); // no arangojs method calls allowed
});
// BAD! The callback should not use any functions that themselves use any
// arangojs methods!
async function saveSomeData() {
await collection.save(data);
await collection.save(moreData);
}
await trx.step(() => saveSomeData()); // WRONG
// BETTER: Pass the transaction to functions that need to call arangojs
// methods inside a transaction
async function saveSomeData(trx) {
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
}
await saveSomeData(); // no `trx.step` call needed
// BAD! You must wait for the promise to resolve (or await on the
// `trx.step` call) before calling `trx.step` again!
trx.step(() => collection.save(data)); // WRONG
await trx.step(() => collection.save(moreData));
// BAD! The trx.step callback can not make multiple calls to async arangojs
// methods, not even using Promise.all!
await trx.step(() => Promise.all([ // WRONG
collection.save(data),
collection.save(moreData),
]));
// BAD! Multiple `trx.step` calls can not run in parallel!
await Promise.all([ // WRONG
trx.step(() => collection.save(data)),
trx.step(() => collection.save(moreData)),
]));
// BETTER: Always call `trx.step` sequentially, one after the other
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
// OKAY: The then callback can be used if async/await is not available
trx.step(() => collection.save(data))
.then(() => trx.step(() => collection.save(moreData)));
// BAD! The callback will return an empty promise that resolves before
// the inner arangojs method call has even talked to ArangoDB!
await trx.step(async () => {
collection.save(data); // WRONG
});
// BETTER: Use an arrow function so you don't forget to return
await trx.step(() => collection.save(data));
// OKAY: Remember to always return when using a function body
await trx.step(() => {
return collection.save(data); // easy to forget!
});
// OKAY: You do not have to use arrow functions but it helps
await trx.step(function () {
return collection.save(data);
});
// BAD! You can not pass promises instead of a callback!
await trx.step(collection.save(data)); // WRONG
// BETTER: Wrap the code in a function and pass the function instead
await trx.step(() => collection.save(data));
// WORSE: Calls to non-async arangojs methods don't need to be performed
// as part of a transaction
const collection = await trx.step(() => db.collection("my-documents"));
// BETTER: If an arangojs method is not async and doesn't return promises,
// call it without `trx.step`
const collection = db.collection("my-documents");
Type of the callback's returned promise.
Callback function returning a promise.
Warning: The callback function should wrap a single call of an async
arangojs method (e.g. a method on a Collection
object of a collection
that is involved in the transaction or the db.query
method).
If the callback function is async, only the first promise-returning (or
async) method call will be executed as part of the transaction. See the
examples below for how to avoid common mistakes when using this method.
Note: Avoid defining the callback as an async function if possible as arangojs will throw an error if the callback did not return a promise. Async functions will return an empty promise by default, making it harder to notice if you forgot to return something from the callback.
Note: Although almost anything can be wrapped in a callback and passed to this method, that does not guarantee ArangoDB can actually do it in a transaction. Refer to the ArangoDB documentation if you are unsure whether a given operation can be executed as part of a transaction. Generally any modification or retrieval of data is eligible but modifications of collections or databases are not.
Optional
options: TransactionOptionsOptions for the transaction.
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 ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
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 }));
}
);
Collections that can be read from and written to during the transaction.
Callback function executing the transaction steps.
Executes the given function locally as a single step of the transaction.
const db = new Database();
const vertices = db.collection("vertices");
const edges = db.collection("edges");
const trx = await db.beginTransaction({ write: [vertices, edges] });
// The following code will be part of the transaction
const left = await trx.step(() => vertices.save({ label: "left" }));
const right = await trx.step(() => vertices.save({ label: "right" }));
// Results from preceding actions can be used normally
await trx.step(() => edges.save({
_from: left._id,
_to: right._id,
data: "potato"
}));
// Transaction must be committed for changes to take effected
// Always call either trx.commit or trx.abort to end a transaction
await trx.commit();
// BAD! If the callback is an async function it must only use await once!
await trx.step(async () => {
await collection.save(data);
await collection.save(moreData); // WRONG
});
// BAD! Callback function must use only one arangojs call!
await trx.step(() => {
return collection.save(data)
.then(() => collection.save(moreData)); // WRONG
});
// BETTER: Wrap every arangojs method call that should be part of the
// transaction in a separate `trx.step` call
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
// BAD! If the callback is an async function it must not await before
// calling an arangojs method!
await trx.step(async () => {
await doSomethingElse();
return collection.save(data); // WRONG
});
// BAD! Any arangojs inside the callback must not happen inside a promise
// method!
await trx.step(() => {
return doSomethingElse()
.then(() => collection.save(data)); // WRONG
});
// BETTER: Perform any async logic needed outside the `trx.step` call
await doSomethingElse();
await trx.step(() => collection.save(data));
// OKAY: You can perform async logic in the callback after the arangojs
// method call as long as it does not involve additional arangojs method
// calls, but this makes it easy to make mistakes later
await trx.step(async () => {
await collection.save(data);
await doSomethingDifferent(); // no arangojs method calls allowed
});
// BAD! The callback should not use any functions that themselves use any
// arangojs methods!
async function saveSomeData() {
await collection.save(data);
await collection.save(moreData);
}
await trx.step(() => saveSomeData()); // WRONG
// BETTER: Pass the transaction to functions that need to call arangojs
// methods inside a transaction
async function saveSomeData(trx) {
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
}
await saveSomeData(); // no `trx.step` call needed
// BAD! You must wait for the promise to resolve (or await on the
// `trx.step` call) before calling `trx.step` again!
trx.step(() => collection.save(data)); // WRONG
await trx.step(() => collection.save(moreData));
// BAD! The trx.step callback can not make multiple calls to async arangojs
// methods, not even using Promise.all!
await trx.step(() => Promise.all([ // WRONG
collection.save(data),
collection.save(moreData),
]));
// BAD! Multiple `trx.step` calls can not run in parallel!
await Promise.all([ // WRONG
trx.step(() => collection.save(data)),
trx.step(() => collection.save(moreData)),
]));
// BETTER: Always call `trx.step` sequentially, one after the other
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
// OKAY: The then callback can be used if async/await is not available
trx.step(() => collection.save(data))
.then(() => trx.step(() => collection.save(moreData)));
// BAD! The callback will return an empty promise that resolves before
// the inner arangojs method call has even talked to ArangoDB!
await trx.step(async () => {
collection.save(data); // WRONG
});
// BETTER: Use an arrow function so you don't forget to return
await trx.step(() => collection.save(data));
// OKAY: Remember to always return when using a function body
await trx.step(() => {
return collection.save(data); // easy to forget!
});
// OKAY: You do not have to use arrow functions but it helps
await trx.step(function () {
return collection.save(data);
});
// BAD! You can not pass promises instead of a callback!
await trx.step(collection.save(data)); // WRONG
// BETTER: Wrap the code in a function and pass the function instead
await trx.step(() => collection.save(data));
// WORSE: Calls to non-async arangojs methods don't need to be performed
// as part of a transaction
const collection = await trx.step(() => db.collection("my-documents"));
// BETTER: If an arangojs method is not async and doesn't return promises,
// call it without `trx.step`
const collection = db.collection("my-documents");
Type of the callback's returned promise.
Callback function returning a promise.
Warning: The callback function should wrap a single call of an async
arangojs method (e.g. a method on a Collection
object of a collection
that is involved in the transaction or the db.query
method).
If the callback function is async, only the first promise-returning (or
async) method call will be executed as part of the transaction. See the
examples below for how to avoid common mistakes when using this method.
Note: Avoid defining the callback as an async function if possible as arangojs will throw an error if the callback did not return a promise. Async functions will return an empty promise by default, making it harder to notice if you forgot to return something from the callback.
Note: Although almost anything can be wrapped in a callback and passed to this method, that does not guarantee ArangoDB can actually do it in a transaction. Refer to the ArangoDB documentation if you are unsure whether a given operation can be executed as part of a transaction. Generally any modification or retrieval of data is eligible but modifications of collections or databases are not.
Optional
options: TransactionOptionsOptions for the transaction.
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 ArangoCollection interface: Collection
,
GraphVertexCollection, GraphEdgeCollection as well as
(in TypeScript) DocumentCollection and EdgeCollection.
const vertices = db.collection("vertices");
const start = vertices.document("a");
const end = vertices.document("b");
const edges = db.collection("edges");
await db.withTransaction(
edges, // collection instances can be passed directly
async (step) => {
await step(() => edges.save({ _from: start._id, _to: end._id }));
}
);
A collection that can be read from and written to during the transaction.
Callback function executing the transaction steps.
Executes the given function locally as a single step of the transaction.
const db = new Database();
const vertices = db.collection("vertices");
const edges = db.collection("edges");
const trx = await db.beginTransaction({ write: [vertices, edges] });
// The following code will be part of the transaction
const left = await trx.step(() => vertices.save({ label: "left" }));
const right = await trx.step(() => vertices.save({ label: "right" }));
// Results from preceding actions can be used normally
await trx.step(() => edges.save({
_from: left._id,
_to: right._id,
data: "potato"
}));
// Transaction must be committed for changes to take effected
// Always call either trx.commit or trx.abort to end a transaction
await trx.commit();
// BAD! If the callback is an async function it must only use await once!
await trx.step(async () => {
await collection.save(data);
await collection.save(moreData); // WRONG
});
// BAD! Callback function must use only one arangojs call!
await trx.step(() => {
return collection.save(data)
.then(() => collection.save(moreData)); // WRONG
});
// BETTER: Wrap every arangojs method call that should be part of the
// transaction in a separate `trx.step` call
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
// BAD! If the callback is an async function it must not await before
// calling an arangojs method!
await trx.step(async () => {
await doSomethingElse();
return collection.save(data); // WRONG
});
// BAD! Any arangojs inside the callback must not happen inside a promise
// method!
await trx.step(() => {
return doSomethingElse()
.then(() => collection.save(data)); // WRONG
});
// BETTER: Perform any async logic needed outside the `trx.step` call
await doSomethingElse();
await trx.step(() => collection.save(data));
// OKAY: You can perform async logic in the callback after the arangojs
// method call as long as it does not involve additional arangojs method
// calls, but this makes it easy to make mistakes later
await trx.step(async () => {
await collection.save(data);
await doSomethingDifferent(); // no arangojs method calls allowed
});
// BAD! The callback should not use any functions that themselves use any
// arangojs methods!
async function saveSomeData() {
await collection.save(data);
await collection.save(moreData);
}
await trx.step(() => saveSomeData()); // WRONG
// BETTER: Pass the transaction to functions that need to call arangojs
// methods inside a transaction
async function saveSomeData(trx) {
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
}
await saveSomeData(); // no `trx.step` call needed
// BAD! You must wait for the promise to resolve (or await on the
// `trx.step` call) before calling `trx.step` again!
trx.step(() => collection.save(data)); // WRONG
await trx.step(() => collection.save(moreData));
// BAD! The trx.step callback can not make multiple calls to async arangojs
// methods, not even using Promise.all!
await trx.step(() => Promise.all([ // WRONG
collection.save(data),
collection.save(moreData),
]));
// BAD! Multiple `trx.step` calls can not run in parallel!
await Promise.all([ // WRONG
trx.step(() => collection.save(data)),
trx.step(() => collection.save(moreData)),
]));
// BETTER: Always call `trx.step` sequentially, one after the other
await trx.step(() => collection.save(data));
await trx.step(() => collection.save(moreData));
// OKAY: The then callback can be used if async/await is not available
trx.step(() => collection.save(data))
.then(() => trx.step(() => collection.save(moreData)));
// BAD! The callback will return an empty promise that resolves before
// the inner arangojs method call has even talked to ArangoDB!
await trx.step(async () => {
collection.save(data); // WRONG
});
// BETTER: Use an arrow function so you don't forget to return
await trx.step(() => collection.save(data));
// OKAY: Remember to always return when using a function body
await trx.step(() => {
return collection.save(data); // easy to forget!
});
// OKAY: You do not have to use arrow functions but it helps
await trx.step(function () {
return collection.save(data);
});
// BAD! You can not pass promises instead of a callback!
await trx.step(collection.save(data)); // WRONG
// BETTER: Wrap the code in a function and pass the function instead
await trx.step(() => collection.save(data));
// WORSE: Calls to non-async arangojs methods don't need to be performed
// as part of a transaction
const collection = await trx.step(() => db.collection("my-documents"));
// BETTER: If an arangojs method is not async and doesn't return promises,
// call it without `trx.step`
const collection = db.collection("my-documents");
Type of the callback's returned promise.
Callback function returning a promise.
Warning: The callback function should wrap a single call of an async
arangojs method (e.g. a method on a Collection
object of a collection
that is involved in the transaction or the db.query
method).
If the callback function is async, only the first promise-returning (or
async) method call will be executed as part of the transaction. See the
examples below for how to avoid common mistakes when using this method.
Note: Avoid defining the callback as an async function if possible as arangojs will throw an error if the callback did not return a promise. Async functions will return an empty promise by default, making it harder to notice if you forgot to return something from the callback.
Note: Although almost anything can be wrapped in a callback and passed to this method, that does not guarantee ArangoDB can actually do it in a transaction. Refer to the ArangoDB documentation if you are unsure whether a given operation can be executed as part of a transaction. Generally any modification or retrieval of data is eligible but modifications of collections or databases are not.
Optional
options: TransactionOptionsOptions for the transaction.
Generated using TypeDoc
An object representing a single ArangoDB database. All arangojs collections, cursors, analyzers and so on are linked to a
Database
object.