การเขียน Atlas Functions ด้วย JavaScript
ผู้เรียนจะเขียน Atlas Functions โดยใช้คอนเท็กซ์ออบเจ็กต์เพื่อเข้าถึงบริการที่เชื่อมโยง ตัวแปรสภาพแวดล้อม และไคลเอ็นต์ MongoDB ในตัว
การเขียน Atlas Functions ด้วย JavaScript เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
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
}Accessing MongoDB With context.services
context.services.get('mongodb-atlas') returns a MongoDB client bound to your linked Atlas cluster. From it you get a database handle and then a collection handle — the same API as the Node.js MongoDB driver. Operations are async and should be awaited. The client is pre-configured with the App Services internal credentials, so you do not manage connection strings in function code.
exports = async function() {
// Get the linked MongoDB service
const mongodb = context.services.get('mongodb-atlas')
const db = mongodb.db('mydb')
const orders = db.collection('orders')
// Full CRUD API available
const pending = await orders.find({ status: 'pending' }).toArray()
await orders.updateMany({ status: 'pending' }, { $set: { notified: true } })
return { processed: pending.length }
}Environment Variables: context.values and context.environment
Hardcoding secrets (API keys, passwords) in function code is dangerous. Atlas Functions support two mechanisms for secure config: Values — static strings or secrets stored in App Services and accessed via context.values.get('myValue'). Environment variables — per-environment overrides accessed via context.environment.values.MY_VAR. Use these to store API keys, webhook secrets, and environment-specific settings.
exports = async function() {
// Retrieve a stored secret (never exposed in function logs)
const apiKey = context.values.get('STRIPE_SECRET_KEY')
// Or use environment-specific values
const webhookUrl = context.environment.values.SLACK_WEBHOOK_URL
// Use in an HTTP call
const http = context.services.get('myHTTP')
await http.post({
url: webhookUrl,
headers: { 'Content-Type': ['application/json'] },
body: JSON.stringify({ text: 'Job complete' })
})
}Making HTTP Requests
Atlas Functions can call external REST APIs using a linked HTTP service or the built-in context.http shortcut. This enables integrations with Stripe, SendGrid, Slack, Twilio, GitHub, and any other REST API without deploying additional infrastructure. Always store API keys in Values or Secrets, never in code.
exports = async function(orderId, amount) {
// Create a Stripe payment intent via REST API
const stripeKey = context.values.get('STRIPE_SECRET_KEY')
const response = await context.http.post({
url: 'https://api.stripe.com/v1/payment_intents',
headers: {
'Authorization': ['Bearer ' + stripeKey],
'Content-Type': ['application/x-www-form-urlencoded']
},
body: 'amount=' + Math.round(amount * 100) + '¤cy=usd&metadata[orderId]=' + orderId
})
const body = EJSON.parse(response.body.text())
return body.client_secret
}Calling Other Atlas Functions
Atlas Functions can call each other with context.functions.execute('functionName', arg1, arg2). This promotes reuse — you can write utility functions (send an email, log an event, validate a JWT) once and call them from any trigger or endpoint function. Recursive calls are supported but Atlas limits call depth to prevent infinite recursion.
// Main function calls a utility function
exports = async function(userId) {
const db = context.services.get('mongodb-atlas').db('mydb')
const user = await db.collection('users').findOne({ _id: userId })
// Call a reusable 'sendWelcomeEmail' function
await context.functions.execute('sendWelcomeEmail', user.email, user.name)
return { status: 'welcome email sent' }
}User Context: Who Is Calling?
In functions called by authenticated users (via HTTPS endpoints with user authentication), context.user provides the caller's identity: their user ID, email, roles, and custom data. This lets you build secure, user-scoped logic without passing user IDs manually. Functions invoked by triggers or scheduled jobs have a system-level user context.
// HTTPS endpoint function that is user-scoped
exports = async function({ query, body }) {
// context.user is populated when the endpoint uses user auth
const currentUserId = context.user.id
const db = context.services.get('mongodb-atlas').db('mydb')
// Users can only read their own data
const orders = await db.collection('orders')
.find({ ownerId: currentUserId })
.toArray()
return { orders }
}Error Handling Best Practices
Wrap your function body in try/catch and always re-throw errors after logging them. This ensures Atlas marks the invocation as failed (enabling retry logic for triggers) and the error appears in the execution log with full context. Use structured logging (JSON strings) rather than plain text so logs are machine-parseable.
exports = async function(payload) {
const start = Date.now()
try {
const result = await processPayload(payload)
console.log(JSON.stringify({ status: 'ok', result, ms: Date.now() - start }))
return result
} catch (err) {
console.error(JSON.stringify({
status: 'error',
message: err.message,
stack: err.stack,
ms: Date.now() - start
}))
throw err // re-throw so Atlas marks this invocation as FAILED
}
}Function Execution Limits
Atlas Functions have important execution limits: Maximum runtime: 90 seconds per invocation. Memory: 256 MB. Code size: 64 KB per function. Response size: 4 MB for HTTPS endpoints. For long-running or memory-intensive operations, design your functions to process data in small batches and use multiple invocations (via scheduled triggers) to handle large datasets.
Testing Functions Locally With app-services-cli
You can develop and test Atlas Functions locally using the Atlas App Services CLI (app-services-cli). Push your function code, trigger configurations, and environment values to App Services with a single command. The CLI also supports pulling your existing configuration as code so you can version-control it in Git alongside your application code.
// Install the App Services CLI
// npm install -g atlas-app-services-cli
// Pull existing config
// appservices pull --remote=<app_id>
// Push updated functions
// appservices push --include-node-modules
// Run a function locally (using App Services CLI)
// appservices function run --name=myFunction --arg='{"key":"val"}'Function Naming and Organisation
As your App Services application grows, organise functions with consistent naming conventions. Use prefixes or folders: trigger_onOrderInsert, util_sendEmail, api_getProducts. Keep functions small and focused — a function that does one thing is easier to test, debug, and reuse. Extract shared logic into utility functions and call them with context.functions.execute() from multiple callers.
// Organised function naming examples:
// trigger_onOrderInsert — database trigger handler
// trigger_dailyArchive — scheduled trigger
// api_getOrders — HTTPS endpoint handler
// util_sendEmail — shared email utility
// util_validatePayload — shared validation utility
// Calling a utility from any other function:
await context.functions.execute('util_sendEmail', {
to: user.email,
subject: 'Your order is confirmed',
body: 'Order ID: ' + orderId
})Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: Atlas Functions export a single async function entry point and access MongoDB, HTTP services, and environment config through the global context object, functions can call each other with context.functions.execute() for reusable utility logic, and always re-throw errors after logging so Atlas marks invocations as failed and retries triggers appropriately. Next up we expose Atlas Functions as HTTPS endpoints.
คำถามที่พบบ่อย
บทเรียน “การเขียน Atlas Functions ด้วย JavaScript” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การเขียน Atlas Functions ด้วย JavaScript” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การเขียน Atlas Functions ด้วย JavaScript”
ผู้เรียนจะเขียน Atlas Functions โดยใช้คอนเท็กซ์ออบเจ็กต์เพื่อเข้าถึงบริการที่เชื่อมโยง ตัวแปรสภาพแวดล้อม และไคลเอ็นต์ MongoDB ในตัว คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การเขียน Atlas Functions ด้วย JavaScript” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทริกเกอร์ฐานข้อมูล: การตอบสนองต่อเหตุการณ์ CRUD
- ทริกเกอร์ตามกำหนดเวลาและงาน Cron
- การเขียน Atlas Functions ด้วย JavaScript
- เอนด์พอยต์ HTTPS ในฐานะเว็บฮุกน้ำหนักเบา