An Atlas Function is server-side JavaScript that controls application behavior without requiring you to deploy or maintain a server. Atlas routes a call to a managed server, runs the code, and returns the result. A client application can call a function directly, or an Atlas Trigger can run it automatically. section 19.2.2 section 19.3
Use a function for a short task that needs application logic close to Atlas data:
- Transform or validate data, move data, or access an Atlas cluster through the built-in client. section 19.2.2
- Respond to a database change. A database trigger passes its change event to a function, which can inspect the event and update data or send a notification. section 19.2.2
- Call an external API—for example, to generate a vector representation when a document is inserted—and store the result alongside the document. section 19.2.1
exports = function(name) {
return `Hello, ${name ?? "MongoDB-in-Action"}!`;
}
A minimal function assigns a JavaScript function to `exports`. It accepts a name and returns a greeting, using a default when no name is supplied. section 19.2.2
Functions can call other functions and use global utilities, standard Node.js modules, and npm packages. Their execution context includes the calling user, invocation method, and application state; code can use those details for user-specific behavior. For an external request, use asynchronous JavaScript and check the response before processing it. The illustrated user-data API address is fictional, so replace it before attempting a real integration. section 19.2.2
