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();
HelperDescription
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.

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 collectionDescription / 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]);
return { count: rows.length, rows };
HelperDescription / 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.
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.