SyntaxStudy
Sign Up
MongoDB Atlas Triggers and Functions
MongoDB Beginner 1 min read

Atlas Triggers and Functions

Atlas App Services provides serverless Functions (JavaScript running on the Atlas platform) and Triggers (Functions that fire automatically in response to events). Database Triggers fire when documents are inserted, updated, replaced, or deleted in a watched collection. Scheduled Triggers run on a cron schedule. Authentication Triggers fire on user authentication events. Atlas Functions can call external HTTP endpoints, send emails via third-party services, and access other Atlas collections. They run in a Node.js environment with built-in access to the Atlas SDK. This makes it easy to add server-side logic without maintaining a separate backend service for simple operations like sending a welcome email or invalidating a cache after a database change.
Example
// Atlas Database Trigger — fires on every new order insert
// (Function code, written in the Atlas UI)

exports = async function(changeEvent) {
  // changeEvent.fullDocument is the inserted/updated document
  const order = changeEvent.fullDocument

  // Access another collection via the context
  const db = context.services.get("mongodb-atlas").db("shop")
  const notifications = db.collection("notifications")

  // Insert a notification document
  await notifications.insertOne({
    userId: order.userId,
    message: `Your order #${order._id} has been received.`,
    createdAt: new Date(),
    read: false
  })

  // Call an external webhook (e.g. send email via SendGrid)
  const response = await context.http.post({
    url: "https://api.sendgrid.com/v3/mail/send",
    headers: {
      "Authorization": [`Bearer ${context.values.get("SENDGRID_KEY")}`],
      "Content-Type": ["application/json"]
    },
    body: JSON.stringify({
      to: [{ email: order.customerEmail }],
      from: { email: "noreply@myshop.com" },
      subject: "Order Confirmed",
      content: [{ type: "text/plain", value: `Order ${order._id} confirmed!` }]
    })
  })
  return response.status
}