0Pricing
MongoDB Academy · Lesson

Writing Atlas Functions in JavaScript

Learners will write Atlas Functions using the context object to access linked services, environment variables, and the built-in MongoDB client.

What Are Atlas Functions?

Atlas Functions are server-side JavaScript functions that run in the Atlas App Services managed runtime. They are the execution unit behind database triggers, scheduled triggers, and HTTPS endpoints. Functions have full access to the MongoDB client, environment variables, linked third-party services (HTTP, AWS, Twilio, etc.), and can call other Atlas Functions.

Function Anatomy: exports and context

Every Atlas Function exports a single async function as its entry point via exports = async function(...args) {}. Inside the function, the global context object provides access to Atlas services. The function receives arguments that vary by invocation type: database triggers receive a change event, HTTPS endpoints receive an HTTP request, and called functions receive the arguments passed by the caller.

// Minimal Atlas Function structure
exports = async function(arg1, arg2) {
  // context is globally available
  const db = context.services.get('mongodb-atlas').db('mydb')
  const result = await db.collection('users').findOne({ _id: arg1 })
  return result
}

All lessons in this course

  1. Database Triggers: Reacting to CRUD Events
  2. Scheduled Triggers and Cron Jobs
  3. Writing Atlas Functions in JavaScript
  4. HTTPS Endpoints as Lightweight Webhooks
← Back to MongoDB Academy