Skip to main content

Introduction

MongoDB Stitch is a serverless platform that extends MongoDB, providing functionalities like triggers, user authentication, and data access controls. Although MongoDB has rebranded Stitch to MongoDB Realm, the core functionalities remain similar. Here's how you can use Stitch (or Realm) with MongoDB:

Key Features

  1. Serverless Functions: Write and deploy JavaScript functions that can be triggered by database events, HTTP services, or scheduled intervals.

  2. Triggers: Automatically execute server-side logic in response to changes in the database, such as insertions, updates, or deletions.

  3. User Authentication: Provides built-in authentication providers like Google, Facebook, and custom JWT, making it easier to manage users.

  4. Data Access Rules: Define fine-grained access controls to your MongoDB data based on user roles or document-level permissions.

  5. REST API and GraphQL: Expose your MongoDB data over REST or GraphQL, making it easier to integrate with frontend applications.

  6. Real-time Sync: For mobile applications, Stitch offers real-time data synchronization between the server and client.

How to Use Stitch with MongoDB

  1. Initial Setup:

    • Go to the MongoDB Atlas dashboard and create a new Stitch app linked to your MongoDB cluster.
  2. Define Schema and Rules:

    • Use the Stitch UI to define the schema for your collections and set up data access rules.
  3. User Authentication:

    • Configure one or more authentication providers (e.g., anonymous, email/password, OAuth).
  4. Serverless Functions:

    • Write JavaScript functions for your custom logic and deploy them.
  5. Set Up Triggers:

    • Create database triggers to automatically run functions based on database events.
  6. Client SDKs:

    • Use Stitch client SDKs (available for JavaScript, Android, and iOS) to interact with your Stitch app from your client application.

Example: Database Trigger

Let's say you have a orders collection and you want to automatically update the inventory when a new order is placed.

  1. Create a Function: Write a JavaScript function that decreases the inventory count based on the ordered quantity.

  2. Set Up a Trigger: Create a database trigger that fires this function whenever a new document is inserted into the orders collection.

This way, your inventory will always be up-to-date without requiring any manual intervention.