Creates a new Database
instance with its own connection pool.
See also Database#database.
Optional
config: ConfigAn object with configuration options.
const db = new Database({
url: "http://127.0.0.1:8529",
databaseName: "my_database",
auth: { username: "admin", password: "hunter2" },
});
Creates a new Database
instance with its own connection pool.
See also Database#database.
Base URL of the ArangoDB server or list of server URLs.
Equivalent to the url
option in connection.Config.
Optional
name: stringconst db = new Database("http://127.0.0.1:8529", "my_database");
db.useBasicAuth("admin", "hunter2");
Name 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 connection.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.
If set to true
, the existing host list will be
replaced instead of extended.
const db = new Database();
const interval = setInterval(
() => db.acquireHostList(),
5 * 60 * 1000 // every 5 minutes
);
// later
clearInterval(interval);
system.close();
Returns an analyzer.Analyzer instance representing the Analyzer with the
given analyzerName
.
const db = new Database();
const analyzer = db.analyzer("some-analyzer");
const info = await analyzer.get();
Fetches all Analyzers visible in the database and returns an array of analyzer.Analyzer instances for those Analyzers.
See also Database#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.Transaction instance for the transaction.
Collections can be specified as collection names (strings) or objects
implementing the collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as
well as (in TypeScript) collection.DocumentCollection and
collection.EdgeCollection.
Collections involved in the transaction.
Optional
options: TransactionOptionsOptions for the transaction.
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 transaction.Transaction instance for the transaction.
Collections can be specified as collection names (strings) or objects
implementing the collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.EdgeCollection.
Collections that can be read from and written to during the transaction.
Optional
options: TransactionOptionsOptions for the transaction.
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 transaction.Transaction instance for the transaction.
The Collection can be specified as a collection name (string) or an object
implementing the collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.EdgeCollection.
A collection that can be read from and written to during the transaction.
Optional
options: TransactionOptionsOptions for the transaction.
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();
Clears the list of recent slow queries.
See also Database#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.
Name of the ArangoDB user to clear the access level for.
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".
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 collection.DocumentCollection and collection.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.
Name of the edge collection.
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>;
Fetches all collections from the database and returns an array of
Collection
instances.
In TypeScript these instances implement both the collection.DocumentCollection and collection.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.
See also Database#listCollections.
Whether system collections should be excluded.
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
Writes all locally available services to the database and updates any service bundles missing in the database.
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.
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
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.Analyzer instance for the new Analyzer.
Name of the Analyzer.
An object defining the properties of the Analyzer.
const db = new Database();
const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });
// the identity Analyzer "potatoes" now exists
Creates a new collection with the given collectionName
and options
,
then returns a collection.DocumentCollection instance for the new collection.
Name of the new collection.
Optional
options: CreateCollectionOptions & { Options for creating the collection.
const db = new Database();
const documents = db.createCollection("persons");
interface Person {
name: string;
}
const db = new Database();
const documents = db.createCollection<Person>("persons");
Creates a new edge collection with the given collectionName
and
options
, then returns an collection.EdgeCollection instance for the new
edge collection.
Name of the new collection.
Options for creating the 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
});
Creates a new database with the given databaseName
with the given
options
and returns a Database
instance for that database.
Name of the database to create.
Optional
options: CreateDatabaseOptionsOptions for creating the database.
const db = new Database();
const info = await db.createDatabase("mydb", {
users: [{ username: "root" }]
});
// the database has been created
Creates a new database with the given databaseName
with the given
users
and returns a Database
instance for that database.
Name of the database to create.
Database users to create with the database.
const db = new Database();
const info = await db.createDatabase("mydb", [{ username: "root" }]);
// the database has been created
Creates a new edge collection with the given collectionName
and
options
, then returns an collection.EdgeCollection instance for the new
edge collection.
This is a convenience method for calling Database#createCollection
with options.type
set to EDGE_COLLECTION
.
Name of the new collection.
Optional
options: CreateCollectionOptionsOptions for creating the 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");
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.
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.
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
Creates a graph with the given graphName
and edgeDefinitions
, then
returns a graph.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.
Options for creating the backup.
const info = await db.createHotBackup();
// a hot backup has been created
Creates an async job by executing the given callback function. The first database request performed by the callback will be marked for asynchronous execution and its result will be made available as an async job.
Returns a 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
Creates a new ArangoDB user with the given password.
Name of the ArangoDB user to create.
Password of the new ArangoDB user.
const db = new Database();
const user = await db.createUser("steve", "hunter2");
// The user "steve" has been created
Creates a new ArangoDB user with the given options.
Name of the ArangoDB user to create.
Additional options for creating the ArangoDB user.
const db = new Database();
const user = await db.createUser("steve", { passwd: "hunter2" });
// The user "steve" has been created
Creates a new View with the given viewName
and options
, then returns a
view.View instance for the new View.
Name of the View.
An object defining the properties of the View.
const db = new Database();
const view = await db.createView("potatoes", { type: "arangosearch" });
// the ArangoSearch View "potatoes" now exists
Creates a new Database
instance for the given databaseName
that
shares this database's connection pool.
See also :constructor.
Name of the database.
const systemDb = new Database();
const myDb = system.database("my_database");
Fetches all databases from the server and returns an array of Database
instances for those databases.
See also Database#listDatabases and Database#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.
The expiration timestamp in milliseconds.
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
Retrieves a zip bundle containing the service files.
Returns a Buffer
in node.js or Blob
in the browser.
The service's mount point, relative to the database.
const db = new Database();
const serviceBundle = await db.downloadService("/my-foxx");
Deletes the AQL user function with the given name from the database.
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.
const db = new Database();
await db.dropFunction("ACME::ACCOUNTING::CALCULATE_VAT");
// the function no longer exists
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 collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.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.
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.
const db = new Database();
const action = `
function(params) {
// This code will be executed inside ArangoDB!
const { query } = require("@arangodb");
return query\`
FOR user IN _users
FILTER user.age > ${params.age}
RETURN u.user
\`.toArray();
}
`);
const result = await db.executeTransaction({
read: ["_users"]
}, action, {
params: { age: 12 }
});
// result contains the return value of the action
Performs a server-side transaction and returns its return value.
Collections can be specified as collection names (strings) or objects
implementing the collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.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.
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.
const db = new Database();
const action = `
function(params) {
// This code will be executed inside ArangoDB!
const { query } = require("@arangodb");
return query\`
FOR user IN _users
FILTER user.age > ${params.age}
RETURN u.user
\`.toArray();
}
`);
const result = await db.executeTransaction(["_users"], action, {
params: { age: 12 }
});
// result contains the return value of the action
Performs a server-side transaction and returns its return value.
The Collection can be specified as a collection name (string) or an object
implementing the collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.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.
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.
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
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.
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql!aql template string.
Optional
options: ExplainOptions & { Options for explaining the query.
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.
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql!aql template string.
Optional
options: ExplainOptions & { Options for explaining the query.
const db = new Database();
const collection = db.collection("some-collection");
const explanation = await db.explain(
aql`
FOR doc IN ${collection}
FILTER doc.flavor == "strawberry"
RETURN doc._key
`,
{ allPlans: true }
);
Explains a database query using the given query
and bindVars
.
See the aql!aql template string handler for a safer and easier alternative to passing strings directly.
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.
const db = new Database();
const collection = db.collection("some-collection");
const explanation = await db.explain(
`
FOR doc IN @@collection
FILTER doc.flavor == "strawberry"
RETURN doc._key
`,
{ "@collection": collection.name }
);
Explains a database query using the given query
and bindVars
.
See the aql!aql template string handler for a safer and easier alternative to passing strings directly.
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.
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 }
);
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.
Optional
options: LogEntriesOptionsOptions for retrieving the log entries.
const log = await db.getLogEntries();
for (let i = 0; i < log.totalAmount; i++) {
console.log(`${
new Date(log.timestamp[i] * 1000).toISOString()
} - [${LogLevel[log.level[i]]}] ${log.text[i]} (#${log.lid[i]})`);
}
Retrieves the server's current log level for each topic.
const levels = await db.getLogLevel();
console.log(levels.request); // log level for incoming requests
Retrieves the log messages from the server's global log.
Optional
options: LogEntriesOptionsOptions for retrieving the log entries.
This endpoint has been deprecated in ArangoDB 3.8. Use Database#getLogEntries instead.
const messages = await db.getLogMessages();
for (const m of messages) {
console.log(`${m.date} - [${m.level}] ${m.message} (#${m.id})`);
}
Retrieves information about a mounted service.
The service's mount point, relative to the database.
const db = new Database();
const info = await db.getService("/my-service");
// info contains detailed information about the service
Retrieves information about the service's configuration options and their current values.
See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.
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.
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.
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.
const db = new Database();
const config = await db.getServiceConfiguration("/my-service", true);
for (const [key, value] of Object.entries(config)) {
console.log(`${key}: ${value}`);
}
Retrieves information about the service's dependencies and their current mount points.
See also Database#replaceServiceDependencies and Database#updateServiceDependencies.
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.
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.
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.
const db = new Database();
const deps = await db.getServiceDependencies("/my-service", true);
for (const [key, value] of Object.entries(deps)) {
console.log(`${key}: ${value}`);
}
Retrieves an Open API compatible Swagger API description object for the service installed at the given mount point.
The service's mount point, relative to the database.
const db = new Database();
const spec = await db.getServiceDocumentation("/my-service");
// spec is a Swagger API description of the service
Retrieves the text content of the service's README
or README.md
file.
Returns undefined
if no such file could be found.
The service's mount point, relative to the database.
const db = new Database();
const readme = await db.getServiceReadme("/my-service");
if (readme !== undefined) console.log(readme);
else console.warn(`No README found.`)
Fetches the user data of a single ArangoDB user.
Name of the ArangoDB user to fetch.
const db = new Database();
const user = await db.getUser("steve");
// user is the user object for the user named "steve"
Fetches the given ArangoDB user's access level for the database, or the given collection in the given database.
Name of the ArangoDB user to fetch the access level for.
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".
Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases.
Name of the ArangoDB user to fetch the access levels for.
Optional
full: falseWhether access levels for collections should be included.
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.
Name of the ArangoDB user to fetch the access levels for.
Whether access levels for collections should be included.
const db = new Database();
const accessLevels = await db.getUserDatabases("steve", true);
for (const [databaseName, obj] of Object.entries(accessLevels)) {
console.log(`${databaseName}: ${obj.permission}`);
for (const [collectionName, accessLevel] of Object.entries(obj.collections)) {
console.log(`${databaseName}/${collectionName}: ${accessLevel}`);
}
}
Returns a graph.Graph instance representing the graph with the given
graphName
.
Name of the graph.
const db = new Database();
const graph = db.graph("some-graph");
Fetches all graphs from the database and returns an array of graph.Graph instances for those graphs.
See also Database#listGraphs.
const db = new Database();
const graphs = await db.graphs();
// graphs is an array of Graph instances
Installs a new service.
The service's mount point, relative to the database.
The service bundle to install.
Options for installing the service.
const db = new Database();
// Using a Buffer in Node.js as source
const source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);
const info = await db.installService("/hello", source);
const db = new Database();
// Using a Blob in Node.js as source
const source = await fs.openAsBlob("./my-foxx-service.zip");
const info = await db.installService("/hello", source);
const db = new Database();
// Using a File from a browser file input as source
const element = document.getElementById("my-file-input");
const source = element.files[0];
const info = await db.installService("/hello", source);
Kills a running query with the given queryId
.
See also Database#listRunningQueries.
The ID of a currently running query.
const db = new Database();
const queries = await db.listRunningQueries();
await Promise.all(queries.map(
async (query) => {
if (query.state === "executing") {
await db.killQuery(query.id);
}
}
));
Fetches all Analyzers visible in the database and returns an array of Analyzer descriptions.
See also Database#analyzers.
const db = new Database();
const analyzers = await db.listAnalyzers();
// analyzers is an array of Analyzer descriptions
Fetches all collections from the database and returns an array of collection descriptions.
See also Database#collections.
Whether system collections should be excluded.
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
Fetches all databases from the server and returns an array of their names.
See also Database#databases and Database#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);
Fetches all graphs from the database and returns an array of graph descriptions.
See also Database#graphs.
const db = new Database();
const graphs = await db.listGraphs();
// graphs is an array of graph descriptions
(Enterprise Edition only.) Retrieves a list of all locally found hot backups.
Optional
id: string | string[]If specified, only the backup with the given ID will be returned.
const backups = await db.listHotBackups();
for (const backup of backups) {
console.log(backup.id);
}
Fetches a list of information for all currently running queries.
See also Database#listSlowQueries and Database#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.
The service's mount point, relative to the database.
const db = new Database();
const scripts = await db.listServiceScripts("/my-service");
for (const [name, title] of Object.entries(scripts)) {
console.log(`${name}: ${title}`);
}
Fetches a list of all installed service.
Whether system services should be excluded.
const db = new Database();
const services = await db.listServices();
const db = new Database();
const services = await db.listServices(false); // all services
Fetches a list of information for all recent slow queries.
See also Database#listRunningQueries and Database#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 Database#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 Database#userDatabases and Database#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 Database#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.
The username to authenticate with.
The password to authenticate with.
const db = new Database();
await db.login("admin", "hunter2");
// with an authentication token for the "admin" user.
Parses the given query and returns the result.
See the aql!aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
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.
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
`);
Performs a database query using the given query
, then returns a new
cursor.ArrayCursor instance for the result set.
See the aql!aql template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.
Note: When executing a query in a streaming transaction using the
step
method, the resulting cursor will be bound to that transaction and
you do not need to use the step
method to consume it.
An object containing an AQL query string and bind parameters, e.g. the object returned from an aql!aql template string.
Optional
options: QueryOptionsOptions for the query execution.
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 }
});
Performs a database query using the given query
and bindVars
, then
returns a new cursor.ArrayCursor instance for the result set.
See the aql!aql template string handler for a safer and easier alternative to passing strings directly.
Note: When executing a query in a streaming transaction using the
step
method, the resulting cursor will be bound to that transaction and
you do not need to use the step
method to consume it.
An AQL query string.
Optional
bindVars: Record<string, any>An object defining bind parameters for the query.
Optional
options: QueryOptionsOptions for the query execution.
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 }
);
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.
Options for query tracking.
const db = new Database();
// track up to 5 slow queries exceeding 5 seconds execution time
await db.setQueryTracking({
enabled: true,
trackSlowQueries: true,
maxSlowQueries: 5,
slowQueryThreshold: 5
});
Computes a set of move shard operations to rebalance the cluster and executes them.
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.
Name of the ArangoDB user to remove.
const db = new Database();
await db.removeUser("steve");
// The user "steve" has been removed
Renames the collection collectionName
to newName
.
Additionally removes any stored Collection
instance for
collectionName
from the Database
instance's internal cache.
Note: Renaming collections may not be supported when ArangoDB is running in a cluster configuration.
Current name of the collection.
The new name of the collection.
Renames the view viewName
to newName
.
Additionally removes any stored view.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 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.
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.
The service's mount point, relative to the database.
The service bundle to install.
Options for replacing the service.
const db = new Database();
// Using a Buffer in Node.js as source
const source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);
const info = await db.replaceService("/hello", source);
const db = new Database();
// Using a Blob in Node.js as source
const source = await fs.openAsBlob("./my-foxx-service.zip");
const info = await db.replaceService("/hello", source);
const db = new Database();
// Using a File from a browser file input as source
const element = document.getElementById("my-file-input");
const source = element.files[0];
const info = await db.replaceService("/hello", source);
Replaces the configuration of the given service, discarding any existing values for options not specified.
See also Database#updateServiceConfiguration and Database#getServiceConfiguration.
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.
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.
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.
const db = new Database();
const config = { currency: "USD", locale: "en-US" };
const info = await db.replaceServiceConfiguration("/my-service", config);
for (const [key, value] of Object.entries(info.values)) {
console.log(`${key}: ${value}`);
if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
}
Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.
See also Database#updateServiceDependencies and Database#getServiceDependencies.
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.
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.
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.
const db = new Database();
const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
const info = await db.replaceServiceDependencies(
"/my-service",
deps,
true
);
for (const [key, value] of Object.entries(info)) {
console.log(`${key}: ${value}`);
if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
}
Replaces the ArangoDB user's option with the new options.
Name of the ArangoDB user to modify.
New options to replace the user's existing 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
(Enteprise Edition only.) Restores a consistent local hot backup.
Returns the directory path of the restored backup.
The ID of the backup to restore.
await db.restoreHotBackup("2023-09-19T15.38.21Z_example");
// the backup has been restored
Returns a new route.Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.
Optional
path: stringThe database-relative URL of the route. Defaults to the database API root.
Optional
headers: Headers | Record<string, string>Default headers that should be sent with each request to the route.
const db = new Database();
const myFoxxService = db.route("my-foxx-service");
const response = await myFoxxService.post("users", {
username: "admin",
password: "hunter2"
});
// response.body is the result of
// POST /_db/_system/my-foxx-service/users
// with JSON request body '{"username": "admin", "password": "hunter2"}'
Executes a service script and retrieves its result exposed as
module.exports
(if any).
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.
const db = new Database();
const result = await db.runServiceScript(
"/my-service",
"create-user",
{
username: "service_admin",
password: "hunter2"
}
);
Runs the tests of a given service and returns the results using the "default" reporter.
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"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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
const db = new Database();
const xml = await db.runServiceTests(
"/my-foxx",
{ reporter: "xunit", idiomatic: true }
);
Sets the server's log level for each of the given topics to the given level.
Any omitted topics will be left unchanged.
An object mapping topic names to log levels.
await db.setLogLevel({ request: "debug" });
// Debug information will now be logged for each request
Sets the limit for the number of values of the most recently received server-reported queue times that can be accessed using Database#queueTime.
Number of values to maintain.
Enables or disables development mode for the given service.
The service's mount point, relative to the database.
Whether development mode should be enabled or disabled.
const db = new Database();
await db.setServiceDevelopmentMode("/my-service", true);
// the service is now in development mode
await db.setServiceDevelopmentMode("/my-service", false);
// the service is now in production mode
Sets the given ArangoDB user's access level for the database, or the given collection in the given database.
Name of the ArangoDB user to set the access level for.
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".
Returns a transaction.Transaction instance for an existing streaming
transaction with the given id
.
See also Database#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.Transaction instances for those transactions.
See also Database#listTransactions.
const db = new Database();
const transactions = await db.transactions();
// transactions is an array of transactions
Completely removes a service from the database.
The service's mount point, relative to the database.
Optional
options: UninstallServiceOptionsOptions for uninstalling the service.
const db = new Database();
await db.uninstallService("/my-foxx");
Updates the configuration of the given service while maintaining any existing values for options not specified.
See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.
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.
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.
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.
const db = new Database();
const config = { currency: "USD", locale: "en-US" };
const info = await db.updateServiceConfiguration("/my-service", config);
for (const [key, value] of Object.entries(info.values)) {
console.log(`${key}: ${value}`);
if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
}
Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.
See also Database#replaceServiceDependencies and Database#getServiceDependencies.
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.
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.
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.
const db = new Database();
const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
const info = await db.updateServiceDependencies(
"/my-service",
deps,
true
);
for (const [key, value] of Object.entries(info)) {
console.log(`${key}: ${value}`);
if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
}
Sets the password of a given ArangoDB user to the new value.
Name of the ArangoDB user to change the password for.
New password for the ArangoDB user.
const db = new Database();
const user = await db.updateUser("steve", "hunter2");
// The user "steve" has received a new password
Updates the ArangoDB user with the new options.
Name of the ArangoDB user to modify.
Options of the ArangoDB user to modify.
const db = new Database();
const user = await db.updateUser("steve", { active: false });
// The user "steve" has been set to inactive
Replaces an existing service with a new service while retaining the old service's configuration and dependencies.
The service's mount point, relative to the database.
The service bundle to install.
Options for upgrading the service.
const db = new Database();
// Using a Buffer in Node.js as source
const source = new Blob([await fs.readFileSync("./my-foxx-service.zip")]);
const info = await db.upgradeService("/hello", source);
const db = new Database();
// Using a Blob in Node.js as source
const source = await fs.openAsBlob("./my-foxx-service.zip");
const info = await db.upgradeService("/hello", source);
const db = new Database();
// Using a File from a browser file input as source
const element = document.getElementById("my-file-input");
const source = element.files[0];
const info = await db.upgradeService("/hello", source);
Updates the underlying connection's authorization
header to use Basic
authentication with the given username
and password
, then returns
itself.
The username to authenticate with.
The password to authenticate with.
const db = new Database();
db.useBasicAuth("admin", "hunter2");
// with the username "admin" and password "hunter2".
Updates the underlying connection's authorization
header to use Bearer
authentication with the given authentication token
, then returns itself.
The token to authenticate with.
const db = new Database();
db.useBearerAuth("keyboardcat");
// The database instance now uses Bearer authentication.
Fetches all databases accessible to the active user from the server and
returns an array of Database
instances for those databases.
See also Database#listUserDatabases and Database#databases.
const db = new Database();
const names = await db.userDatabases();
// databases is an array of databases
Fetches version information from the ArangoDB server.
Optional
details: booleanIf set to true
, additional information about the
ArangoDB server will be available as the details
property.
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
Fetches all Views from the database and returns an array of view.View instances for the Views.
See also Database#listViews.
const db = new Database();
const views = await db.views();
// views is an array of ArangoSearch View instances
Performs a request against every known coordinator and returns when the request has succeeded against every coordinator or the timeout is reached.
Note: This method is primarily intended to make database setup easier in cluster scenarios and requires all coordinators to be known to arangojs before the method is invoked. The method is not useful in single-server or leader-follower replication scenarios.
Request to perform against each known coordinator.
Optional
timeout: numberMaximum number of milliseconds to wait for propagation.
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
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 collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as
well as (in TypeScript) collection.DocumentCollection and
collection.EdgeCollection.
Collections involved in the transaction.
Callback function executing the transaction steps.
Executes the given function locally as a single step of the transaction.
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.
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");
Optional
options: TransactionOptionsOptions for the transaction.
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 collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.EdgeCollection.
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.
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.
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");
Optional
options: TransactionOptionsOptions for the transaction.
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 collection.ArangoCollection interface: Collection
,
graph.GraphVertexCollection, graph.GraphEdgeCollection as well as
(in TypeScript) collection.DocumentCollection and collection.EdgeCollection.
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.
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.
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");
Optional
options: TransactionOptionsOptions for the transaction.
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 }));
}
);
An object representing a single ArangoDB database. All arangojs collections, cursors, analyzers and so on are linked to a
Database
object.