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.collection
to 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.collectionName
to get the prefixed collection name ArangoDB understands:
"use strict";
const { db } = require("@arangodb");
const collectionName = module.context.collectionName("users");
if (!db._collection(collectionName)) {
db._createDocumentCollection(collectionName);
}
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._collection
method 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:
// in the service's main file:
exports.users = module.context.collection("users");
// in a dependent service's code:
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.