Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

MongoDB Stitch: Serverless Compute With a Big Difference

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

MongoDB Stitch (now part of MongoDB Atlas App Services) provides serverless compute that is tightly integrated with your database, so you can run functions, triggers, and authentication without managing servers. The big difference is that Stitch is designed for MongoDB-first applications: it gives you a managed backend that speaks directly to your Atlas cluster, handles user authentication, and lets you write JavaScript functions that run in the cloud. To get started, you need an Atlas account and a cluster.

What You'll Need

  • A MongoDB Atlas account (free tier available).
  • An Atlas cluster (M0 free tier is sufficient for testing).
  • A MongoDB user with read/write access to the cluster.
  • Basic knowledge of JavaScript and MongoDB queries.
  • Node.js and npm installed if you plan to use the Stitch CLI or SDK locally.
  • The Stitch CLI (optional but recommended for local development and deployment).

Step-by-Step

  1. Create an Atlas cluster. Log in to MongoDB Atlas, create a new project, and build a cluster. For testing, choose the free M0 tier. Wait for the cluster to be provisioned (usually a few minutes).
  2. Enable Stitch (App Services). In the Atlas sidebar, click “App Services” (or “Stitch” in older interfaces). Click “Create a new application.” Give it a name, link it to your Atlas cluster, and choose a deployment region. Note that menu labels may vary slightly by version or region.
  3. Set up authentication. In the App Services dashboard, go to “Authentication” and enable at least one provider. The simplest is “API Keys” for server-to-server calls, or “Email/Password” for user login. Configure the provider settings and save.
  4. Define a database user and rules. Under “Rules,” create a rule for your database and collection. Set the read and write permissions. For example, allow users to read only their own documents by using a filter like {"owner_id": "%%user.id"}. This is where Stitch’s tight integration with MongoDB shines: you can enforce security at the document level.
  5. Create a Stitch Function. Go to “Functions” and click “Create New Function.” Name it (e.g., addTask), choose “System” for the run-as user (or “User” if you want it to run with the caller’s permissions), and write JavaScript. For example:
    exports = async function(taskName) {
      const mongodb = context.services.get("mongodb-atlas");
      const tasks = mongodb.db("todo").collection("tasks");
      const result = await tasks.insertOne({
        name: taskName,
        owner_id: context.user.id,
        created: new Date()
      });
      return result.insertedId;
    };
    Save the function. You can test it directly in the console.
  6. Set up a trigger (optional). To run code automatically when data changes, go to “Triggers” and create a database trigger. Choose the cluster, database, and collection, and select the operation types (insert, update, delete). Link it to a function. For example, you could send a notification when a new task is added.
  7. Connect from your app. Use the Stitch SDK for your platform (JavaScript, Android, iOS, etc.) or call functions via the REST API. For a web app, install the Stitch JS SDK: npm install mongodb-stitch-browser-sdk. Initialize the client with your App ID (found in the App Services dashboard under “Settings” > “App ID”). Then authenticate and call the function:
    import { Stitch, AnonymousCredential } from 'mongodb-stitch-browser-sdk';
    const client = Stitch.initializeDefaultAppClient('your-app-id');
    client.auth.loginWithCredential(new AnonymousCredential()).then(() => {
      return client.callFunction('addTask', ['Buy milk']);
    }).then(result => console.log(result));
    Note: The SDKs have been updated over time; check the official documentation for the latest package names and methods.
  8. Deploy and monitor. Use the Stitch CLI to push local changes to the cloud. Run stitch-cli login and stitch-cli import to deploy your app configuration. Monitor function logs in the App Services dashboard under “Logs” to debug issues.

Common Mistakes

  • Forgetting to set database rules. Without rules, your data may be wide open or completely inaccessible. Always define rules that match your security model.
  • Using the wrong run-as user. Functions run as either “System” (full access) or “User” (limited by rules). Choose carefully; a system function can bypass rules, which is powerful but risky.
  • Not handling errors in functions. Unhandled exceptions will cause the function to fail silently from the client’s perspective. Always use try/catch and return meaningful errors.
  • Ignoring cold starts. Serverless functions may have a cold start latency. For latency-sensitive operations, keep functions warm or consider dedicated compute.
  • Misconfiguring triggers. Triggers can fire on every document change, leading to unexpected costs or infinite loops if a trigger writes to the same collection. Test triggers in a staging environment.

Tips

  • Use environment variables in Stitch to store secrets like API keys instead of hardcoding them.
  • Leverage the built-in MongoDB query API inside functions; you can use the same drivers you know.
  • Start with the free tier to experiment, but monitor usage as your app grows.
  • Use the Stitch CLI to version-control your app configuration and deploy consistently.
  • Combine Stitch with Atlas Data Lake or Charts for analytics without extra servers.

Troubleshooting

If your function fails, first check the logs in the App Services dashboard. Common issues include incorrect database names, missing permissions, or syntax errors. If authentication fails, verify that the provider is enabled and that the user exists. For triggers not firing, ensure the trigger is enabled and that the linked function has the correct permissions. If you get a “service not found” error, confirm that the service name in context.services.get() matches the linked cluster name (usually “mongodb-atlas”). For SDK connection issues, check that your App ID is correct and that your network allows outbound HTTPS. If you recently changed rules, allow a few minutes for propagation. As a last resort, use the “Logs” section to trace requests and errors.

Frequently Asked Questions

Is Stitch still available?

Stitch has been rebranded as MongoDB Atlas App Services. The core functionality remains, but the interface and SDKs have evolved. Use the current App Services documentation.

Can I use Stitch with a self-hosted MongoDB?

No, Stitch is tightly integrated with Atlas. You need an Atlas cluster to use App Services.

What languages can I write functions in?

Functions are written in JavaScript (Node.js). You can also call functions from various client SDKs.

How do I secure my data?

Use database rules to define per-document access. Combine with authentication providers to ensure only authorized users can access data.

Are there limits on function execution time?

Yes, functions have a maximum execution time (typically 15 minutes for triggers, shorter for called functions). Check the current limits in the documentation.

Can I use Stitch for free?

The free tier includes a limited amount of compute and data transfer. For production, you may need a paid tier. Check Atlas pricing for details.