Working with collections

Foxx provides the module.context.collection methodto provide easy access to ArangoDB collections. These collections are alsocalled “prefixed collections” because Foxx will automatically prefix the namebased on the mount path of the service.

The prefixes may initially feel unnecessarily verbose but help avoid conflictsbetween different services with similar collection names or even multiplecopies of the same service sharing the same database. Keep in mind that youcan also use collection objects when writing queries,so you don’t need to worry about writing out prefixes by hand.

As a rule of thumb you should always use module.context.collectionto access collections in your service.

Low-level collection access

ArangoDB provides alow-level API for managing collectionsvia the db object.These APIs are not very useful for most application logic but allow you tocreate and destroy collections in yourlifecycle scripts and migrations.

Using these methods requires you to work with fully qualified collection names.This means instead of using module.context.collection to get acollection object you need to use module.context.collectionNameto get the prefixed collection name ArangoDB understands:

  1. "use strict";
  2. const { db } = require("@arangodb");
  3. const collectionName = module.context.collectionName("users");
  4. if (!db._collection(collectionName)) {
  5. db._createDocumentCollection(collectionName);
  6. }

Sharing collections

The most obvious way to share collections between multiple services is to usean unprefixed collection name and then use the low-level db._collectionmethod to access that collection from each service that needs access to it.

The downside of this approach is that it results in an implicit dependency ofthose services on a single collection as well as creating the potential forsubtle problems if a different service uses the same unprefixedcollection name in the future.

The cleanest approach is to instead decide on a single service which managesthe collection and set up explicit dependencies betweenthe different services using the collection:

  1. // in the service's main file:
  2. exports.users = module.context.collection("users");
  3. // in a dependent service's code:
  4. const users = module.dependencies.usersService.users;

This approach not only makes the dependency on an externally managed collectionexplicit but also allows having those services still use different collectionsif necessary by providing multiple copies of the service that provides theshared collection.