arangodb-node 使用

Posted 79 months ago nodejs nosql arangodb

Install

With NPM

npm install arangojs

With bower

bower install arangojs

From source

git clone https://github.com/arangodb/arangojs.git
cd arangojs
npm install
npm run dist

Basic usage example

// ES2015-style
import arangojs, {Database, aql} from 'arangojs';
let db1 = arangojs(); // convenience short-hand
let db2 = new Database();
let {query, bindVars} = aql`RETURN ${Date.now()}`;

// or plain old Node-style
var arangojs = require('arangojs');
var db1 = arangojs();
var db2 = new arangojs.Database();
var aql = arangojs.aql(['RETURN ', ''], Date.now());
var query = aql.query;
var bindVars = aql.bindVars;

API

All asynchronous functions take an optional Node-style callback (or “errback”) as the last argument with the following arguments:

For expected API errors, err will be an instance of ArangoError. For any other error responses (4xx/5xx status code), err will be an instance of the apropriate http-errors error type. If the response indicates success but the response body could not be parsed, err will be a SyntaxError. In all of these cases the error object will additionally have a response property containing the server response object.

If Promise is defined globally, asynchronous functions return a promise if no callback is provided.

If you want to use promises in environments that don’t provide the global Promise constructor, use a promise polyfill like es6-promise or inject a ES6-compatible promise implementation like bluebird into the global scope.

Examples

// Node-style callbacks
db.createDatabase('mydb', function (err, info) {
    if (err) console.error(err.stack);
    else {
        // database created
    }
});

// Using promises with ES2015 arrow functions
db.createDatabase('mydb')
.then(info => {
    // database created
}, err => console.error(err.stack));

// Using proposed ES.next "async/await" syntax
try {
    let info = await db.createDatabase('mydb');
    // database created
} catch (err) {
    console.error(err.stack);
}

Table of Contents

Database API

new Database

new Database([config]): Database

Creates a new Database instance.

If config is a string, it will be interpreted as config.url.

Arguments

Manipulating databases

These functions implement the HTTP API for manipulating databases.

database.useDatabase

database.useDatabase(databaseName): this

Updates the Database instance and its connection string to use the given databaseName, then returns itself.

Arguments

Examples

var db = require('arangojs')();
db.useDatabase('test');
// The database instance now uses the database "test".

database.createDatabase

async database.createDatabase(databaseName, [users]): Object

Creates a new database with the given databaseName.

Arguments

Examples

var db = require('arangojs')();
db.createDatabase('mydb', [{username: 'root'}])
.then(info => {
    // the database has been created
});

database.get

async database.get(): Object

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

Examples

var db = require('arangojs')();
db.get()
.then(info => {
    // the database exists
});

database.listDatabases

async database.listDatabases(): Array string

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

Examples

var db = require('arangojs')();
db.listDatabases()
.then(names => {
    // databases is an array of database names
});

database.listUserDatabases

async database.listUserDatabases(): Array string

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

Examples

var db = require('arangojs')();
db.listUserDatabases()
.then(names => {
    // databases is an array of database names
});

database.dropDatabase

async database.dropDatabase(databaseName): Object

Deletes the database with the given databaseName from the server.

var db = require('arangojs')();
db.dropDatabase('mydb')
.then(() => {
    // database "mydb" no longer exists
})

database.truncate

async database.truncate([excludeSystem]): Object

Deletes all documents in all collections in the active database.

Arguments

Examples

var db = require('arangojs')();

db.truncate()
.then(() => {
    // all non-system collections in this database are now empty
});

// -- or --

db.truncate(false)
.then(() => {
    // I've made a huge mistake...
});

Accessing collections

These functions implement the HTTP API for accessing collections.

database.collection

database.collection(collectionName): DocumentCollection

Returns a DocumentCollection instance for the given collection name.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('potatos');

database.edgeCollection

database.edgeCollection(collectionName): EdgeCollection

Returns an EdgeCollection instance for the given collection name.

Arguments

Examples

var db = require('arangojs')();
var collection = db.edgeCollection('potatos');

database.listCollections

async database.listCollections([excludeSystem]): ArrayObject

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

Arguments

Examples

var db = require('arangojs')();

db.listCollections()
.then(collections => {
    // collections is an array of collection descriptions
    // not including system collections
});

// -- or --

db.listCollections(false)
.then(collections => {
    // collections is an array of collection descriptions
    // including system collections
});

database.collections

async database.collections([excludeSystem]): Array<Collection>

Fetches all collections from the database and returns an array of DocumentCollection and EdgeCollection instances for the collections.

Arguments

Examples

var db = require('arangojs')();

db.listCollections()
.then(collections => {
    // collections is an array of DocumentCollection
    // and EdgeCollection instances
    // not including system collections
});

// -- or --

db.listCollections(false)
.then(collections => {
    // collections is an array of DocumentCollection
    // and EdgeCollection instances
    // including system collections
});

Accessing graphs

These functions implement the HTTP API for accessing general graphs.

database.graph

database.graph(graphName): Graph

Returns a Graph instance representing the graph with the given graph name.

database.listGraphs

async database.listGraphs(): ArrayObject

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

Examples

var db = require('arangojs')();
db.listGraphs()
.then(graphs => {
    // graphs is an array of graph descriptions
});

database.graphs

async database.graphs(): Array<Graph>

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

Examples

var db = require('arangojs')();
db.graphs()
.then(graphs => {
    // graphs is an array of Graph instances
});

Transactions

This function implements the HTTP API for transactions.

database.transaction

async database.transaction(collections, action, [params,] [lockTimeout]): Object

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

Arguments

If collections is an array or string, it will be treated as collections.write.

Please note that while action should be a string evaluating to a well-formed JavaScript function, it’s not possible to pass in a JavaScript function directly because the function needs to be evaluated on the server and will be transmitted in plain text.

For more information on transactions, see the HTTP API documentation for transactions.

Examples

var db = require('arangojs')();
var action = String(function () {
    // This code will be executed inside ArangoDB!
    var db = require('org/arangodb').db;
    return db._query('FOR user IN _users RETURN u.user').toArray<any>();
});
db.transaction({read: '_users'}, action)
.then(result => {
    // result contains the return value of the action
});

Queries

This function implements the HTTP API for single roundtrip AQL queries.

For collection-specific queries see simple queries.

database.query

async database.query(query, [bindVars,] [opts]): Cursor

Performs a database query using the given query and bindVars, then returns a new Cursor instance for the result list.

Arguments

If opts.count is set to true, the cursor will have a count property set to the query result count.

If query is an object with query and bindVars properties, those will be used as the values of the respective arguments instead.

Examples

var db = require('arangojs')();
var active = true;

// Using ES2015 string templates
var aql = require('arangojs').aql;
db.query(aql`
    FOR u IN _users
    FILTER u.authData.active == ${active}
    RETURN u.user
`)
.then(cursor => {
    // cursor is a cursor for the query result
});

// -- or --

// Using the query builder
var qb = require('aqb');
db.query(
    qb.for('u').in('_users')
    .filter(qb.eq('u.authData.active', '@active'))
    .return('u.user'),
    {active: true}
)
.then(cursor => {
    // cursor is a cursor for the query result
});

// -- or --

// Using plain arguments
db.query(
    'FOR u IN _users'
    + ' FILTER u.authData.active == @active'
    + ' RETURN u.user',
    {active: true}
)
.then(cursor => {
    // cursor is a cursor for the query result
});

aql

aql(strings, ...args): Object

Template string handler for AQL queries. Converts an ES2015 template string to an object that can be passed to database.query by converting arguments to bind variables.

Any Collection instances will automatically be converted to collection bind variables.

Examples

var db = require('arangojs')();
var aql = require('arangojs').aql;
var userCollection = db.collection('_users');
var role = 'admin';
db.query(aql`
    FOR user IN ${userCollection}
    FILTER user.role == ${role}
    RETURN user
`)
.then(cursor => {
    // cursor is a cursor for the query result
});
// -- is equivalent to --
db.query(
  'FOR user IN @@value0 FILTER user.role == @value1 RETURN user',
  {'@value0': userCollection.name, value1: role}
)
.then(cursor => {
    // cursor is a cursor for the query result
});

Managing AQL user functions

These functions implement the HTTP API for managing AQL user functions.

database.listFunctions

async database.listFunctions(): ArrayObject

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

Examples

var db = require('arangojs')();
db.listFunctions()
.then(functions => {
    // functions is a list of function descriptions
})

database.createFunction

async database.createFunction(name, code): Object

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.

Arguments

Examples

var db = require('arangojs')();
var aql = require('arangojs').aql;
db.createFunction(
  'ACME::ACCOUNTING::CALCULATE_VAT',
  String(function (price) {
      return price * 0.19;
  })
)
// Use the new function in an AQL query with template handler:
.then(() => db.query(aql`
    FOR product IN products
    RETURN MERGE(
      {vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price)},
      product
    )
`))
.then(cursor => {
    // cursor is a cursor for the query result
});

database.dropFunction

async database.dropFunction(name, [group]): Object

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

Arguments

Examples

var db = require('arangojs')();
db.dropFunction('ACME::ACCOUNTING::CALCULATE_VAT')
.then(() => {
    // the function no longer exists
});

Arbitrary HTTP routes

database.route

database.route([path,] [headers]): Route

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

Arguments

If path is missing, the route will refer to the base URL of the database.

For more information on Route instances see the Route API below.

Examples

var db = require('arangojs')();
var myFoxxService = db.route('my-foxx-service');
myFoxxService.post('users', {
    username: 'admin',
    password: 'hunter2'
})
.then(response => {
    // response.body is the result of
    // POST /_db/_system/my-foxx-service/users
    // with JSON request body '{"username": "admin", "password": "hunter2"}'
});

Cursor API

Cursor instances provide an abstraction over the HTTP API’s limitations. Unless a method explicitly exhausts the cursor, the driver will only fetch as many batches from the server as necessary. Like the server-side cursors, Cursor instances are incrementally depleted as they are read from.

var db = require('arangojs')();
db.query('FOR x IN 1..100 RETURN x')
// query result list: [1, 2, 3, ..., 99, 100]
.then(cursor => {
    cursor.next())
    .then(value => {
        value === 1;
        // remaining result list: [2, 3, 4, ..., 99, 100]
    });
});

cursor.count

cursor.count: number

The total number of documents in the query result. This is only available if the count option was used.

cursor.all

async cursor.all(): ArrayObject

Exhausts the cursor, then returns an array containing all values in the cursor’s remaining result list.

Examples

// query result list: [1, 2, 3, 4, 5]
cursor.all()
.then(vals => {
    // vals is an array containing the entire query result
    Array.isArray(vals);
    vals.length === 5;
    vals; // [1, 2, 3, 4, 5]
    cursor.hasNext() === false;
});

cursor.next

async cursor.next(): Object

Advances the cursor and returns the next value in the cursor’s remaining result list. If the cursor has already been exhausted, returns undefined instead.

Examples

// query result list: [1, 2, 3, 4, 5]
cursor.next()
.then(val => {
    val === 1;
    // remaining result list: [2, 3, 4, 5]
    return cursor.next();
})
.then(val2 => {
    val2 === 2;
    // remaining result list: [3, 4, 5]
});

cursor.hasNext

cursor.hasNext(): boolean

Returns true if the cursor has more values or false if the cursor has been exhausted.

Examples

cursor.all() // exhausts the cursor
.then(() => {
    cursor.hasNext() === false;
});

cursor.each

async cursor.each(fn): any

Advances the cursor by applying the function fn to each value in the cursor’s remaining result list until the cursor is exhausted or fn explicitly returns false.

Returns the last return value of fn.

Equivalent to Array.prototype.forEach (except async).

Arguments

Examples

var results = [];
function doStuff(value) {
    var VALUE = value.toUpperCase();
    results.push(VALUE);
    return VALUE;
}
// query result list: ['a', 'b', 'c']
cursor.each(doStuff)
.then(last => {
    String(results) === 'A,B,C';
    cursor.hasNext() === false;
    last === 'C';
});

cursor.every

async cursor.every(fn): boolean

Advances the cursor by applying the function fn to each value in the cursor’s remaining result list until the cursor is exhausted or fn returns a value that evaluates to false.

Returns false if fn returned a value that evalutes to false, or true otherwise.

Equivalent to Array.prototype.every (except async).

Arguments

function even(value) {
    return value % 2 === 0;
}
// query result list: [0, 2, 4, 5, 6]
cursor.every(even)
.then(result => {
    result === false; // 5 is not even
    cursor.hasNext() === true;
    cursor.next()
    .then(value => {
        value === 6; // next value after 5
    });
});

cursor.some

async cursor.some(fn): boolean

Advances the cursor by applying the function fn to each value in the cursor’s remaining result list until the cursor is exhausted or fn returns a value that evaluates to true.

Returns true if fn returned a value that evalutes to true, or false otherwise.

Equivalent to Array.prototype.some (except async).

Examples

function even(value) {
    return value % 2 === 0;
}
// query result list: [1, 3, 4, 5]
cursor.some(even)
.then(result => {
    result === true; // 4 is even
    cursor.hasNext() === true;
    cursor.next()
    .then(value => {
        value === 5; // next value after 4
    });
});

cursor.map

cursor.map(fn): Array<any>

Advances the cursor by applying the function fn to each value in the cursor’s remaining result list until the cursor is exhausted.

Returns an array of the return values of fn.

Equivalent to Array.prototype.map (except async).

Arguments

Examples

function square(value) {
    return value * value;
}
// query result list: [1, 2, 3, 4, 5]
cursor.map(square)
.then(result => {
    result.length === 5;
    result; // [1, 4, 9, 16, 25]
    cursor.hasNext() === false;
});

cursor.reduce

cursor.reduce(fn, [accu]): any

Exhausts the cursor by reducing the values in the cursor’s remaining result list with the given function fn. If accu is not provided, the first value in the cursor’s remaining result list will be used instead (the function will not be invoked for that value).

Equivalent to Array.prototype.reduce (except async).

Arguments

Examples

function add(a, b) {
    return a + b;
}
// query result list: [1, 2, 3, 4, 5]

var baseline = 1000;
cursor.reduce(add, baseline)
.then(result => {
    result === (baseline + 1 + 2 + 3 + 4 + 5);
    cursor.hasNext() === false;
});

// -- or --

cursor.reduce(add)
.then(result => {
    result === (1 + 2 + 3 + 4 + 5);
    cursor.hasNext() === false;
});

Route API

Route instances provide access for arbitrary HTTP requests. This allows easy access to Foxx services and other HTTP APIs not covered by the driver itself.

route.route

route.route([path], [headers]): Route

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

Arguments

If path is missing, the route will refer to the base URL of the database.

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
var users = route.route('users');
// equivalent to db.route('my-foxx-service/users')

route.get

async route.get([path,] [qs]): Response

Performs a GET request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.get()
.then(response => {
    // response.body is the response body of calling
    // GET _db/_system/my-foxx-service
});

// -- or --

route.get('users')
.then(response => {
    // response.body is the response body of calling
    // GET _db/_system/my-foxx-service/users
});

// -- or --

route.get('users', {group: 'admin'})
.then(response => {
    // response.body is the response body of calling
    // GET _db/_system/my-foxx-service/users?group=admin
});

route.post

async route.post([path,] [body, [qs]]): Response

Performs a POST request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.post()
.then(response => {
    // response.body is the response body of calling
    // POST _db/_system/my-foxx-service
});

// -- or --

route.post('users')
.then(response => {
    // response.body is the response body of calling
    // POST _db/_system/my-foxx-service/users
});

// -- or --

route.post('users', {
    username: 'admin',
    password: 'hunter2'
})
.then(response => {
    // response.body is the response body of calling
    // POST _db/_system/my-foxx-service/users
    // with JSON request body {"username": "admin", "password": "hunter2"}
});

// -- or --

route.post('users', {
    username: 'admin',
    password: 'hunter2'
}, {admin: true})
.then(response => {
    // response.body is the response body of calling
    // POST _db/_system/my-foxx-service/users?admin=true
    // with JSON request body {"username": "admin", "password": "hunter2"}
});

route.put

async route.put([path,] [body, [qs]]): Response

Performs a PUT request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.put()
.then(response => {
    // response.body is the response body of calling
    // PUT _db/_system/my-foxx-service
});

// -- or --

route.put('users/admin')
.then(response => {
    // response.body is the response body of calling
    // PUT _db/_system/my-foxx-service/users
});

// -- or --

route.put('users/admin', {
    username: 'admin',
    password: 'hunter2'
})
.then(response => {
    // response.body is the response body of calling
    // PUT _db/_system/my-foxx-service/users/admin
    // with JSON request body {"username": "admin", "password": "hunter2"}
});

// -- or --

route.put('users/admin', {
    username: 'admin',
    password: 'hunter2'
}, {admin: true})
.then(response => {
    // response.body is the response body of calling
    // PUT _db/_system/my-foxx-service/users/admin?admin=true
    // with JSON request body {"username": "admin", "password": "hunter2"}
});

route.patch

async route.patch([path,] [body, [qs]]): Response

Performs a PATCH request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.patch()
.then(response => {
    // response.body is the response body of calling
    // PATCH _db/_system/my-foxx-service
});

// -- or --

route.patch('users/admin')
.then(response => {
    // response.body is the response body of calling
    // PATCH _db/_system/my-foxx-service/users
});

// -- or --

route.patch('users/admin', {
    password: 'hunter2'
})
.then(response => {
    // response.body is the response body of calling
    // PATCH _db/_system/my-foxx-service/users/admin
    // with JSON request body {"password": "hunter2"}
});

// -- or --

route.patch('users/admin', {
    password: 'hunter2'
}, {admin: true})
.then(response => {
    // response.body is the response body of calling
    // PATCH _db/_system/my-foxx-service/users/admin?admin=true
    // with JSON request body {"password": "hunter2"}
});

route.delete

async route.delete([path,] [qs]): Response

Performs a DELETE request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.delete()
.then(response => {
    // response.body is the response body of calling
    // DELETE _db/_system/my-foxx-service
});

// -- or --

route.delete('users/admin')
.then(response => {
    // response.body is the response body of calling
    // DELETE _db/_system/my-foxx-service/users/admin
});

// -- or --

route.delete('users/admin', {permanent: true})
.then(response => {
    // response.body is the response body of calling
    // DELETE _db/_system/my-foxx-service/users/admin?permanent=true
});

route.head

async route.head([path,] [qs]): Response

Performs a HEAD request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.head()
.then(response => {
    // response is the response object for
    // HEAD _db/_system/my-foxx-service
});

route.request

async route.request([opts]): Response

Performs an arbitrary request to the given URL and returns the server response.

Arguments

Examples

var db = require('arangojs')();
var route = db.route('my-foxx-service');
route.request({
    path: 'hello-world',
    method: 'POST',
    body: {hello: 'world'},
    qs: {admin: true}
})
.then(response => {
    // response.body is the response body of calling
    // POST _db/_system/my-foxx-service/hello-world?admin=true
    // with JSON request body '{"hello": "world"}'
});

Collection API

These functions implement the HTTP API for manipulating collections.

The Collection API is implemented by all Collection instances, regardless of their specific type. I.e. it represents a shared subset between instances of DocumentCollection, EdgeCollection, GraphVertexCollection and GraphEdgeCollection.

Getting information about the collection

See the HTTP API documentation for details.

collection.get

async collection.get(): Object

Retrieves general information about the collection.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.get()
.then(data => {
    // data contains general information about the collection
});

collection.properties

async collection.properties(): Object

Retrieves the collection’s properties.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.properties()
.then(data => {
    // data contains the collection's properties
});

collection.count

async collection.count(): Object

Retrieves information about the number of documents in a collection.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.count()
.then(data => {
    // data contains the collection's count
});

collection.figures

async collection.figures(): Object

Retrieves statistics for a collection.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.figures()
.then(data => {
    // data contains the collection's figures
});

collection.revision

async collection.revision(): Object

Retrieves the collection revision ID.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.revision()
.then(data => {
    // data contains the collection's revision
});

collection.checksum

async collection.checksum([opts]): Object

Retrieves the collection checksum.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.checksum()
.then(data => {
    // data contains the collection's checksum
});

Manipulating the collection

These functions implement the HTTP API for modifying collections.

collection.create

async collection.create([properties]): Object

Creates a collection with the given properties for this collection’s name, then returns the server response.

Arguments

Examples

var db = require('arangojs')();
collection = db.collection('potatos');
collection.create()
.then(() => {
    // the document collection "potatos" now exists
});

// -- or --

var collection = var collection = db.edgeCollection('friends');
collection.create({
    waitForSync: true // always sync document changes to disk
})
.then(() => {
    // the edge collection "friends" now exists
});

collection.load

async collection.load([count]): Object

Tells the server to load the collection into memory.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.load(false)
.then(() => {
    // the collection has now been loaded into memory
});

collection.unload

async collection.unload(): Object

Tells the server to remove the collection from memory.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.unload()
.then(() => {
    // the collection has now been unloaded from memory
});

collection.setProperties

async collection.setProperties(properties): Object

Replaces the properties of the collection.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.setProperties({waitForSync: true})
.then(result => {
    result.waitForSync === true;
    // the collection will now wait for data being written to disk
    // whenever a document is changed
});

collection.rename

async collection.rename(name): Object

Renames the collection. The Collection instance will automatically update its name when the rename succeeds.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.rename('new-collection-name')
.then(result => {
    result.name === 'new-collection-name';
    collection.name === result.name;
    // result contains additional information about the collection
});

collection.rotate

async collection.rotate(): Object

Rotates the journal of the collection.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.rotate()
.then(data => {
    // data.result will be true if rotation succeeded
});

collection.truncate

async collection.truncate(): Object

Deletes all documents in the collection in the database.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.truncate()
.then(() => {
    // the collection "some-collection" is now empty
});

collection.drop

async collection.drop(): Object

Deletes the collection from the database.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.drop()
.then(() => {
    // the collection "some-collection" no longer exists
});

Manipulating indexes

These functions implement the HTTP API for manipulating indexes.

collection.createIndex

async collection.createIndex(details): Object

Creates an arbitrary index on the collection.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.createIndex({type: 'cap', size: 20})
.then(index => {
    index.id; // the index's handle
    // the index has been created
});

collection.createCapConstraint

async collection.createCapConstraint(size): Object

Creates a cap constraint index on the collection.

Note: This method is not available when using the driver with ArangoDB 3.0 and higher as cap constraints are no longer supported.

Arguments

If size is a number, it will be interpreted as size.size.

For more information on the properties of the size object see the HTTP API for creating cap constraints.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');

collection.createCapConstraint(20)
.then(index => {
    index.id; // the index's handle
    index.size === 20;
    // the index has been created
});

// -- or --

collection.createCapConstraint({size: 20})
.then(index => {
    index.id; // the index's handle
    index.size === 20;
    // the index has been created
});

collection.createHashIndex

async collection.createHashIndex(fields, [opts]): Object

Creates a hash index on the collection.

Arguments

For more information on hash indexes, see the HTTP API for hash indexes.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');

collection.createHashIndex('favorite-color')
.then(index => {
    index.id; // the index's handle
    index.fields; // ['favorite-color']
    // the index has been created
});

// -- or --

collection.createHashIndex(['favorite-color'])
.then(index => {
    index.id; // the index's handle
    index.fields; // ['favorite-color']
    // the index has been created
});

collection.createSkipList

async collection.createSkipList(fields, [opts]): Object

Creates a skiplist index on the collection.

Arguments

For more information on skiplist indexes, see the HTTP API for skiplist indexes.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');

collection.createSkipList('favorite-color')
.then(index => {
    index.id; // the index's handle
    index.fields; // ['favorite-color']
    // the index has been created
});

// -- or --

collection.createSkipList(['favorite-color'])
.then(index => {
    index.id; // the index's handle
    index.fields; // ['favorite-color']
    // the index has been created
});

collection.createGeoIndex

async collection.createGeoIndex(fields, [opts]): Object

Creates a geo-spatial index on the collection.

Arguments

For more information on the properties of the opts object see the HTTP API for manipulating geo indexes.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');

collection.createGeoIndex(['longitude', 'latitude'])
.then(index => {
    index.id; // the index's handle
    index.fields; // ['longitude', 'latitude']
    // the index has been created
});

// -- or --

collection.createGeoIndex('location', {geoJson: true})
.then(index => {
    index.id; // the index's handle
    index.fields; // ['location']
    // the index has been created
});

collection.createFulltextIndex

async collection.createFulltextIndex(fields, [minLength]): Object

Creates a fulltext index on the collection.

Arguments

For more information on fulltext indexes, see the HTTP API for fulltext indexes.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');

collection.createFulltextIndex('description')
.then(index => {
    index.id; // the index's handle
    index.fields; // ['description']
    // the index has been created
});

// -- or --

collection.createFulltextIndex(['description'])
.then(index => {
    index.id; // the index's handle
    index.fields; // ['description']
    // the index has been created
});

collection.index

async collection.index(indexHandle): Object

Fetches information about the index with the given indexHandle and returns it.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.createFulltextIndex('description')
.then(index => {
    collection.index(index.id)
    .then(result => {
        result.id === index.id;
        // result contains the properties of the index
    });

    // -- or --

    collection.index(index.id.split('/')[1])
    .then(result => {
        result.id === index.id;
        // result contains the properties of the index
    });
});

collection.indexes

async collection.indexes(): ArrayObject

Fetches a list of all indexes on this collection.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.createFulltextIndex('description')
.then(() => collection.indexes())
.then(indexes => {
    indexes.length === 1;
    // indexes contains information about the index
});

collection.dropIndex

async collection.dropIndex(indexHandle): Object

Deletes the index with the given indexHandle from the collection.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
collection.createFulltextIndex('description')
.then(index => {
    collection.dropIndex(index.id)
    .then(() => {
        // the index has been removed from the collection
    });

    // -- or --

    collection.dropIndex(index.id.split('/')[1])
    .then(() => {
        // the index has been removed from the collection
    });
});

Simple queries

These functions implement the HTTP API for simple queries.

collection.all

async collection.all([opts]): Cursor

Performs a query to fetch all documents in the collection. Returns a new Cursor instance for the query results.

Arguments

collection.any

async collection.any(): Object

Fetches a document from the collection at random.

collection.first

async collection.first([opts]): ArrayObject

Performs a query to fetch the first documents in the collection. Returns an array of the matching documents.

Note: This method is not available when using the driver with ArangoDB 3.0 and higher as the corresponding API method has been removed.

Arguments

collection.last

async collection.last([opts]): ArrayObject

Performs a query to fetch the last documents in the collection. Returns an array of the matching documents.

Note: This method is not available when using the driver with ArangoDB 3.0 and higher as the corresponding API method has been removed.

Arguments

collection.byExample

async collection.byExample(example, [opts]): Cursor

Performs a query to fetch all documents in the collection matching the given example. Returns a new Cursor instance for the query results.

Arguments

collection.firstExample

async collection.firstExample(example): Object

Fetches the first document in the collection matching the given example.

Arguments

collection.removeByExample

async collection.removeByExample(example, [opts]): Object

Removes all documents in the collection matching the given example.

Arguments

collection.replaceByExample

async collection.replaceByExample(example, newValue, [opts]): Object

Replaces all documents in the collection matching the given example with the given newValue.

Arguments

collection.updateByExample

async collection.updateByExample(example, newValue, [opts]): Object

Updates (patches) all documents in the collection matching the given example with the given newValue.

Arguments

collection.lookupByKeys

async collection.lookupByKeys(keys): ArrayObject

Fetches the documents with the given keys from the collection. Returns an array of the matching documents.

Arguments

collection.removeByKeys

async collection.removeByKeys(keys, [opts]): Object

Deletes the documents with the given keys from the collection.

Arguments

collection.fulltext

async collection.fulltext(fieldName, query, [opts]): Cursor

Performs a fulltext query in the given fieldName on the collection.

Arguments

Bulk importing documents

This function implements the HTTP API for bulk imports.

collection.import

async collection.import(data, [opts]): Object

Bulk imports the given data into the collection.

Arguments

If data is a JavaScript array, it will be transmitted as a line-delimited JSON stream. If opts.type is set to "array", it will be transmitted as regular JSON instead. If data is a string, it will be transmitted as it is without any processing.

For more information on the opts object, see the HTTP API documentation for bulk imports.

Examples

var db = require('arangojs')();
var collection = db.collection('users');

collection.import(
    [// document stream
        {username: 'admin', password: 'hunter2'},
        {username: 'jcd', password: 'bionicman'},
        {username: 'jreyes', password: 'amigo'},
        {username: 'ghermann', password: 'zeitgeist'}
    ]
)
.then(result => {
    result.created === 4;
});

// -- or --

collection.import(
    [// array stream with header
        ['username', 'password'], // keys
        ['admin', 'hunter2'], // row 1
        ['jcd', 'bionicman'], // row 2
        ['jreyes', 'amigo'],
        ['ghermann', 'zeitgeist']
    ]
)
.then(result => {
    result.created === 4;
});

// -- or --

collection.import(
    // raw line-delimited JSON array stream with header
    '["username", "password"]\r\n' +
    '["admin", "hunter2"]\r\n' +
    '["jcd", "bionicman"]\r\n' +
    '["jreyes", "amigo"]\r\n' +
    '["ghermann", "zeitgeist"]\r\n'
)
.then(result => {
    result.created === 4;
});

Manipulating documents

These functions implement the HTTP API for manipulating documents.

collection.replace

async collection.replace(documentHandle, newValue, [opts]): Object

Replaces the content of the document with the given documentHandle with the given newValue and returns an object containing the document’s metadata.

Note: The policy option is not available when using the driver with ArangoDB 3.0 as it is redundant when specifying the rev option.

Arguments

If a string is passed instead of an options object, it will be interpreted as the rev option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
var doc = {number: 1, hello: 'world'};
collection.save(doc)
.then(doc1 => {
    collection.replace(doc1, {number: 2})
    .then(doc2 => {
        doc2._id === doc1._id;
        doc2._rev !== doc1._rev;
        collection.document(doc1)
        .then(doc3 => {
            doc3._id === doc1._id;
            doc3._rev === doc2._rev;
            doc3.number === 2;
            doc3.hello === undefined;
        })
    });
});

collection.update

async collection.update(documentHandle, newValue, [opts]): Object

Updates (merges) the content of the document with the given documentHandle with the given newValue and returns an object containing the document’s metadata.

Note: The policy option is not available when using the driver with ArangoDB 3.0 as it is redundant when specifying the rev option.

Arguments

If a string is passed instead of an options object, it will be interpreted as the rev option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');
var doc = {number: 1, hello: 'world'};
collection.save(doc)
.then(doc1 => {
    collection.update(doc1, {number: 2})
    .then(doc2 => {
        doc2._id === doc1._id;
        doc2._rev !== doc1._rev;
        collection.document(doc2)
        .then(doc3 => {
          doc3._id === doc2._id;
          doc3._rev === doc2._rev;
          doc3.number === 2;
          doc3.hello === doc.hello;
        });
    });
});

collection.remove

async collection.remove(documentHandle, [opts]): Object

Deletes the document with the given documentHandle from the collection.

Note: The policy option is not available when using the driver with ArangoDB 3.0 as it is redundant when specifying the rev option.

Arguments

If a string is passed instead of an options object, it will be interpreted as the rev option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

var db = require('arangojs')();
var collection = db.collection('some-collection');

collection.remove('some-doc')
.then(() => {
    // document 'some-collection/some-doc' no longer exists
});

// -- or --

collection.remove('some-collection/some-doc')
.then(() => {
    // document 'some-collection/some-doc' no longer exists
});

collection.list

async collection.list([type]): Array string

Retrieves a list of references for all documents in the collection.

Arguments

DocumentCollection API

The DocumentCollection API extends the Collection API (see above) with the following methods.

documentCollection.document

async documentCollection.document(documentHandle): Object

Retrieves the document with the given documentHandle from the collection.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('my-docs');

collection.document('some-key')
.then(doc => {
    // the document exists
    doc._key === 'some-key';
    doc._id === 'my-docs/some-key';
});

// -- or --

collection.document('my-docs/some-key')
.then(doc => {
    // the document exists
    doc._key === 'some-key';
    doc._id === 'my-docs/some-key';
});

documentCollection.save

async documentCollection.save(data): Object

Creates a new document with the given data and returns an object containing the document’s metadata.

Arguments

Examples

var db = require('arangojs')();
var collection = db.collection('my-docs');
var doc = {some: 'data'};
collection.save(doc)
.then(doc1 => {
    doc1._key; // the document's key
    doc1._id === ('my-docs/' + doc1._key);
    collection.document(doc)
    .then(doc2 => {
        doc2._id === doc1._id;
        doc2._rev === doc1._rev;
        doc2.some === 'data';
    });
});

EdgeCollection API

The EdgeCollection API extends the Collection API (see above) with the following methods.

edgeCollection.edge

async edgeCollection.edge(documentHandle): Object

Retrieves the edge with the given documentHandle from the collection.

Arguments

Examples

var db = require('arangojs')();
var collection = var collection = db.edgeCollection('edges');

collection.edge('some-key')
.then(edge => {
    // the edge exists
    edge._key === 'some-key';
    edge._id === 'edges/some-key';
});

// -- or --

collection.edge('edges/some-key')
.then(edge => {
    // the edge exists
    edge._key === 'some-key';
    edge._id === 'edges/some-key';
});

edgeCollection.save

async edgeCollection.save(data, [fromId, toId]): Object

Creates a new edge between the documents fromId and toId with the given data and returns an object containing the edge’s metadata.

Arguments

Examples

var db = require('arangojs')();
var collection = db.edgeCollection('edges');
var edge = {some: 'data'};

collection.save(
    edge,
    'vertices/start-vertex',
    'vertices/end-vertex'
)
.then(edge1 => {
    edge1._key; // the edge's key
    edge1._id === ('edges/' + edge1._key);
    collection.edge(edge)
    .then(edge2 => {
        edge2._key === edge1._key;
        edge2._rev = edge1._rev;
        edge2.some === edge.some;
        edge2._from === 'vertices/start-vertex';
        edge2._to === 'vertices/end-vertex';
    });
});

// -- or --

collection.save({
    some: 'data',
    _from: 'verticies/start-vertex',
    _to: 'vertices/end-vertex'
})
.then(edge => {
    // ...
})

edgeCollection.edges

async edgeCollection.edges(documentHandle): ArrayObject

Retrieves a list of all edges of the document with the given documentHandle.

Arguments

Examples

var db = require('arangojs')();
var collection = db.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/a', 'vertices/c'],
    ['z', 'vertices/d', 'vertices/a']
])
.then(() => collection.edges('vertices/a'))
.then(edges => {
    edges.length === 3;
    edges.map(function (edge) {return edge._key;}); // ['x', 'y', 'z']
});

edgeCollection.inEdges

async edgeCollection.inEdges(documentHandle): Array Object

Retrieves a list of all incoming edges of the document with the given documentHandle.

Arguments

Examples

var db = require('arangojs')();
var collection = db.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/a', 'vertices/c'],
    ['z', 'vertices/d', 'vertices/a']
])
.then(() => collection.inEdges('vertices/a'))
.then(edges => {
    edges.length === 1;
    edges[0]._key === 'z';
});

edgeCollection.outEdges

async edgeCollection.outEdges(documentHandle): Array Object

Retrieves a list of all outgoing edges of the document with the given documentHandle.

Arguments

Examples

var db = require('arangojs')();
var collection = db.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/a', 'vertices/c'],
    ['z', 'vertices/d', 'vertices/a']
])
.then(() => collection.outEdges('vertices/a'))
.then(edges => {
    edges.length === 2;
    edges.map(function (edge) {return edge._key;}); // ['x', 'y']
});

edgeCollection.traversal

async edgeCollection.traversal(startVertex, opts): Object

Performs a traversal starting from the given startVertex and following edges contained in this edge collection.

Arguments

Examples

var db = require('arangojs')();
var collection = db.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/b', 'vertices/c'],
    ['z', 'vertices/c', 'vertices/d']
])
.then(() => collection.traversal('vertices/a', {
    direction: 'outbound',
    visitor: 'result.vertices.push(vertex._key);',
    init: 'result.vertices = [];'
}))
.then(result => {
    result.vertices; // ['a', 'b', 'c', 'd']
});

Graph API

These functions implement the HTTP API for manipulating graphs.

graph.get

async graph.get(): Object

Retrieves general information about the graph.

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
graph.get()
.then(data => {
    // data contains general information about the graph
});

graph.create

async graph.create(properties): Object

Creates a graph with the given properties for this graph’s name, then returns the server response.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
graph.create({
    edgeDefinitions: [
        {
            collection: 'edges',
            from: [
                'start-vertices'
            ],
            to: [
                'end-vertices'
            ]
        }
    ]
})
.then(graph => {
    // graph is a Graph instance
    // for more information see the Graph API below
});

graph.drop

async graph.drop([dropCollections]): Object

Deletes the graph from the database.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
graph.drop()
.then(() => {
    // the graph "some-graph" no longer exists
});

Manipulating vertices

graph.vertexCollection

graph.vertexCollection(collectionName): GraphVertexCollection

Returns a new GraphVertexCollection instance with the given name for this graph.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.vertexCollection('vertices');
collection.name === 'vertices';
// collection is a GraphVertexCollection

graph.addVertexCollection

async graph.addVertexCollection(collectionName): Object

Adds the collection with the given collectionName to the graph’s vertex collections.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
graph.addVertexCollection('vertices')
.then(() => {
    // the collection "vertices" has been added to the graph
});

graph.removeVertexCollection

async graph.removeVertexCollection(collectionName, [dropCollection]): Object

Removes the vertex collection with the given collectionName from the graph.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');

graph.removeVertexCollection('vertices')
.then(() => {
    // collection "vertices" has been removed from the graph
});

// -- or --

graph.removeVertexCollection('vertices', true)
.then(() => {
    // collection "vertices" has been removed from the graph
    // the collection has also been dropped from the database
    // this may have been a bad idea
});

Manipulating edges

graph.edgeCollection

graph.edgeCollection(collectionName): GraphEdgeCollection

Returns a new GraphEdgeCollection instance with the given name bound to this graph.

Arguments

Examples

var db = require('arangojs')();
// assuming the collections "edges" and "vertices" exist
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.name === 'edges';
// collection is a GraphEdgeCollection

graph.addEdgeDefinition

async graph.addEdgeDefinition(definition): Object

Adds the given edge definition definition to the graph.

Arguments

Examples

var db = require('arangojs')();
// assuming the collections "edges" and "vertices" exist
var graph = db.graph('some-graph');
graph.addEdgeDefinition({
    collection: 'edges',
    from: ['vertices'],
    to: ['vertices']
})
.then(() => {
    // the edge definition has been added to the graph
});

graph.replaceEdgeDefinition

async graph.replaceEdgeDefinition(collectionName, definition): Object

Replaces the edge definition for the edge collection named collectionName with the given definition.

Arguments

Examples

var db = require('arangojs')();
// assuming the collections "edges", "vertices" and "more-vertices" exist
var graph = db.graph('some-graph');
graph.replaceEdgeDefinition('edges', {
    collection: 'edges',
    from: ['vertices'],
    to: ['more-vertices']
})
.then(() => {
    // the edge definition has been modified
});

graph.removeEdgeDefinition

async graph.removeEdgeDefinition(definitionName, [dropCollection]): Object

Removes the edge definition with the given definitionName form the graph.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');

graph.removeEdgeDefinition('edges')
.then(() => {
    // the edge definition has been removed
});

// -- or --

graph.removeEdgeDefinition('edges', true)
.then(() => {
    // the edge definition has been removed
    // and the edge collection "edges" has been dropped
    // this may have been a bad idea
});

graph.traversal

async graph.traversal(startVertex, opts): Object

Performs a traversal starting from the given startVertex and following edges contained in any of the edge collections of this graph.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/b', 'vertices/c'],
    ['z', 'vertices/c', 'vertices/d']
])
.then(() => graph.traversal('vertices/a', {
    direction: 'outbound',
    visitor: 'result.vertices.push(vertex._key);',
    init: 'result.vertices = [];'
}))
.then(result => {
    result.vertices; // ['a', 'b', 'c', 'd']
});

GraphVertexCollection API

The GraphVertexCollection API extends the Collection API (see above) with the following methods.

graphVertexCollection.remove

async graphVertexCollection.remove(documentHandle): Object

Deletes the vertex with the given documentHandle from the collection.

Arguments

Examples

var graph = db.graph('some-graph');
var collection = graph.vertexCollection('vertices');

collection.remove('some-key')
.then(() => {
    // document 'vertices/some-key' no longer exists
});

// -- or --

collection.remove('vertices/some-key')
.then(() => {
    // document 'vertices/some-key' no longer exists
});

graphVertexCollection.vertex

async graphVertexCollection.vertex(documentHandle): Object

Retrieves the vertex with the given documentHandle from the collection.

Arguments

Examples

var graph = db.graph('some-graph');
var collection = graph.vertexCollection('vertices');

collection.vertex('some-key')
.then(doc => {
    // the vertex exists
    doc._key === 'some-key';
    doc._id === 'vertices/some-key';
});

// -- or --

collection.vertex('vertices/some-key')
.then(doc => {
    // the vertex exists
    doc._key === 'some-key';
    doc._id === 'vertices/some-key';
});

graphVertexCollection.save

async graphVertexCollection.save(data): Object

Creates a new vertex with the given data.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.vertexCollection('vertices');
collection.save({some: 'data'})
.then(doc => {
    doc._key; // the document's key
    doc._id === ('vertices/' + doc._key);
    doc.some === 'data';
});

GraphEdgeCollection API

The GraphEdgeCollection API extends the Collection API (see above) with the following methods.

graphEdgeCollection.remove

async graphEdgeCollection.remove(documentHandle): Object

Deletes the edge with the given documentHandle from the collection.

Arguments

Examples

var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');

collection.remove('some-key')
.then(() => {
    // document 'edges/some-key' no longer exists
});

// -- or --

collection.remove('edges/some-key')
.then(() => {
    // document 'edges/some-key' no longer exists
});

graphEdgeCollection.edge

async graphEdgeCollection.edge(documentHandle): Object

Retrieves the edge with the given documentHandle from the collection.

Arguments

Examples

var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');

collection.edge('some-key')
.then(edge => {
    // the edge exists
    edge._key === 'some-key';
    edge._id === 'edges/some-key';
});

// -- or --

collection.edge('edges/some-key')
.then(edge => {
    // the edge exists
    edge._key === 'some-key';
    edge._id === 'edges/some-key';
});

graphEdgeCollection.save

async graphEdgeCollection.save(data, [fromId, toId]): Object

Creates a new edge between the vertices fromId and toId with the given data.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.save(
    {some: 'data'},
    'vertices/start-vertex',
    'vertices/end-vertex'
)
.then(edge => {
    edge._key; // the edge's key
    edge._id === ('edges/' + edge._key);
    edge.some === 'data';
    edge._from === 'vertices/start-vertex';
    edge._to === 'vertices/end-vertex';
});

graphEdgeCollection.edges

async graphEdgeCollection.edges(documentHandle): Array Object

Retrieves a list of all edges of the document with the given documentHandle.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/a', 'vertices/c'],
    ['z', 'vertices/d', 'vertices/a']
])
.then(() => collection.edges('vertices/a'))
.then(edges => {
    edges.length === 3;
    edges.map(function (edge) {return edge._key;}); // ['x', 'y', 'z']
});

graphEdgeCollection.inEdges

async graphEdgeCollection.inEdges(documentHandle): Array Object

Retrieves a list of all incoming edges of the document with the given documentHandle.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/a', 'vertices/c'],
    ['z', 'vertices/d', 'vertices/a']
])
.then(() => collection.inEdges('vertices/a'))
.then(edges => {
    edges.length === 1;
    edges[0]._key === 'z';
});

graphEdgeCollection.outEdges

async graphEdgeCollection.outEdges(documentHandle): ArrayObject

Retrieves a list of all outgoing edges of the document with the given documentHandle.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/a', 'vertices/c'],
    ['z', 'vertices/d', 'vertices/a']
])
.then(() => collection.outEdges('vertices/a'))
.then(edges => {
    edges.length === 2;
    edges.map(function (edge) {return edge._key;}); // ['x', 'y']
});

graphEdgeCollection.traversal

async graphEdgeCollection.traversal(startVertex, opts): Object

Performs a traversal starting from the given startVertex and following edges contained in this edge collection.

Arguments

Examples

var db = require('arangojs')();
var graph = db.graph('some-graph');
var collection = graph.edgeCollection('edges');
collection.import([
    ['_key', '_from', '_to'],
    ['x', 'vertices/a', 'vertices/b'],
    ['y', 'vertices/b', 'vertices/c'],
    ['z', 'vertices/c', 'vertices/d']
])
.then(() => collection.traversal('vertices/a', {
    direction: 'outbound',
    visitor: 'result.vertices.push(vertex._key);',
    init: 'result.vertices = [];'
}))
.then(result => {
    result.vertices; // ['a', 'b', 'c', 'd']
});

License

The Apache License, Version 2.0. For more information, see the accompanying LICENSE file.

点击评论