Resources
Guides for using iMothership at work
Get started, understand the product, and fix things when they go sideways.
Script API reference
Use these JavaScript helpers inside Work API files and code integrations to query collections, connect to external MongoDB databases, and work with imported files.
These are calls on the injected api object. For HTTP endpoints, authentication, request bodies, and responses, see the public HTTP API documentation.
Calling the API
Your script receives body as its input. Use await for database operations and return for the result; no Express req or res is needed. Call toArray() to execute a find or aggregation cursor.
const accounts = api.collection('accounts');
return await accounts.find({ active: true })
.sort({ name: 1 }).limit(50).toArray();| Helper | Description |
|---|---|
api.collection(name) | Access a Mothership collection using the current execution’s collection permissions. Also supports api.collection.accounts. |
api.getCollection(name) | Secure-mode alias for api.collection(name). The injected db.collection(name) also uses the same approved collection rules. |
api.approvedCollections() | Return the configured approved collection names. An empty list is not a list of all database collections. |
await api.mongoDb.connect(uri, dbName?) | Connect to an external MongoDB database. Returns collection(name), db.collection(name), and async close(). Available in secure and non-secure execution. |
external.collection(name) | Access a collection on this external connection. Names are case-sensitive; access follows the supplied MongoDB credentials. |
await external.close() | Close this connection. Safe to call repeatedly. Connections are also cleaned up at the end of the execution. |
Connect to external MongoDB
Use api.mongoDb.connect(uri, dbName) with a mongodb:// or mongodb+srv:// URI. If you omit the database name, the MongoDB driver uses the database from the URI, or its default database. The connection is separate from Mothership’s own collections.
The example uses project tags for the URI and database name. Each tag must resolve to a valid JavaScript string expression. Keep credentials in your project configuration, and do not return them from the script.
const external = await api.mongoDb.connect(
{{ mongodb_uri }},
{{ db_name }}
);
try {
const accounts = external.collection('accounts');
const pipeline = [
{ $match: { AccountType: body.type } },
{ $lookup: {
from: 'countries',
localField: 'Address3',
foreignField: '_id',
as: 'Address3'
} },
{ $unwind: { path: '$Address3', preserveNullAndEmptyArrays: true } }
];
return await accounts.aggregate(pipeline, { allowDiskUse: true }).toArray();
} finally {
await external.close();
}The lookup above assumes matching field types. If your IDs use different types, retain your existing $lookup pipeline with $convert. You can keep an existing pipeline and change only the connection and collection calls.
external.db.collection(name) is an alias for external.collection(name). Use try/finally to close the connection. Automatic cleanup also runs after success or failure. Connections and handles are valid only for the current execution.
In secure mode, MongoDB operations run through the server while your script remains in its sandbox. The database must accept connections from the server network. Host-file TLS options and host-identity authentication are unavailable; use credentials supplied in the URI. The older mongoExternal.connect helper remains non-secure only.
Read-only report execution also supports api.mongoDb.connect for reads. Write methods and write aggregation stages remain unavailable in reports.
Mailbox counts
Use await api.mail.count(options) to count messages in an authorised Microsoft mailbox. Available in secure and non-secure execution for task integrations and Work API scripts with an organisation and project context.
const count = await api.mail.count({
email: 'mailbox@example.com',
folder: 'Inbox/Orders'
});
return { count }; // e.g. { count: 42 }| Option | Description |
|---|---|
email | Required mailbox email address. The mailbox user must belong to the current project and have granted Microsoft inbox access using Give permission to access inbox. Email addresses are trimmed and converted to lowercase. |
folder | Required folder display-name path, such as Inbox or Inbox/Orders. Use the mailbox's actual folder names, including localised names where applicable. Separate nested folders with /. |
Returns a number, including 0 for an empty folder. Counts both read and unread messages directly in that folder; messages in child folders are excluded. This call does not download message bodies, mark messages as read, move messages, or create folders.
Missing folders, unauthorised mailboxes, expired or revoked permissions, and provider failures throw an error rather than returning zero. Existing saved Microsoft authorisation is reused and refreshed on the server; tokens are not returned to your code. Gmail and access to other shared mailboxes through a delegate's account are not supported by this helper.
Collection operations
Use these methods on api.collection(name) or external.collection(name). Unless shown with a cursor, call them with await. Mothership collections remain subject to their approved collection rules; external collections use the permissions of the supplied database account.
| Method on a collection | Description / result |
|---|---|
find(filter?, options?).toArray() | Return all matching documents. Chain sort, limit, skip, or project before toArray. |
find(filter?, options?).next() | Return the first matching document, or null. tryNext() is also supported. |
findOne(filter?, options?) | Return one matching document, or null. |
aggregate(pipeline?, options?).toArray() | Run an aggregation pipeline and return its documents. Supports MongoDB stages such as $match, $lookup and $unwind. |
countDocuments(filter?, options?) | Return the number of matching documents. |
insertOne(document, options?) | Insert one document; returns an acknowledgement and insertedId. |
insertMany(documents, options?) | Insert an array of documents; returns insertedCount and insertedIds. |
updateOne(filter, update, options?) | Update one matching document with operators such as $set; returns matchedCount and modifiedCount. |
updateMany(filter, update, options?) | Update matching documents; returns matchedCount and modifiedCount. |
replaceOne(filter, replacement, options?) | Replace one matching document. |
deleteOne(filter, options?) | Delete one matching document; returns deletedCount. |
deleteMany(filter, options?) | Delete matching documents; returns deletedCount. |
findOneAndUpdate(filter, update, options?) | Update one document and return the driver result. Use returnDocument: "after" for the updated document. |
findOneAndReplace(filter, replacement, options?) | Replace one document and return the driver result. |
findOneAndDelete(filter, options?) | Delete one document and return the driver result. |
bulkWrite(operations, options?) | Run a batch of insert, update, replace, or delete operations and return write counts. |
For find cursors, sort(spec), limit(count), skip(count), and project(fields) configure the query. Secure-mode cursors expose this documented subset of the MongoDB driver; they do not expose a raw MongoClient.
Imported files — secure mode
These helpers are available in secure execution when the job supplies imported file paths in gcsFilePaths. Reads are restricted to those files; uploads must stay alongside an imported file. Size and row limits apply.
const rows = await api.files.parseImportedCsv(gcsFilePaths[0], {
separator: '|',
maxRows: 500000,
maxBytes: 25 * 1024 * 1024,
encoding: 'win1252' // Optional; defaults to 'utf8'
});
return { count: rows.length, rows };For CSV files, the optional encoding selects how the original file bytes are decoded before parsing, including column headers. Supported values are utf8 / utf-8 (default), win1252 / windows-1252 / cp1252, and latin1 / iso-8859-1. Names are case-insensitive. Unsupported values throw an error.
Choose the encoding used by the source file; it is not detected automatically. Windows-1252 and Latin-1 differ for characters such as the euro symbol and curly quotes. Existing calls without encoding continue to use UTF-8.
| Helper | Description / result |
|---|---|
await api.files.readImportedFile(gcsPath, options?) | Read an imported file as text. The path must be available in gcsFilePaths. |
await api.files.parseImportedCsv(gcsPath, options?) | Parse an imported CSV file into an array of row objects. Options include separator (default comma), maxRows (default 50,000; maximum 500,000), maxBytes (default 25 MiB; maximum 100 MiB), and encoding (default utf8). |
await api.files.parseImportedExcel(gcsPath, options?) | Read an imported Excel workbook. Returns worksheets with name, rowCount, columnCount, and rows. Options include sheetName, zero-based sheetIndex, maxRows, and includeEmpty. |
await api.files.upload(destinationGcsPath, content, options?) | Upload content alongside an imported file. Returns ok, path, sizeBytes, and contentType. Options include contentType, encoding, overwrite, and maxBytes. |