NOSQL

Exploring MongoDB Realm

Exploring MongoDB Realm: Real-Time Sync, Serverless Applications, and Custom Functions

April 15, 2011 by Kinshuk Dutta

MongoDB Realm, an extension of MongoDB Atlas, provides powerful tools for building mobile and web applications with real-time synchronization, serverless functions, and a rich set of services for managing complex data workflows. Whether you’re building a mobile app that requires real-time data sync or a serverless application that responds to data changes instantly, MongoDB Realm simplifies development by handling much of the infrastructure complexity.

In this blog, we’ll dive into the key features of MongoDB Realm and walk through building a sample application with real-time data sync, serverless functions, and custom workflows.


Table of Contents

  1. Introduction to MongoDB Realm
  2. Key Features of MongoDB Realm
  3. Setting Up MongoDB Realm
  4. Real-Time Data Synchronization
  5. Serverless Functions
  6. Custom Functions and Triggers
  7. Sample Project: Real-Time Collaboration App with MongoDB Realm
  8. Conclusion and Next Steps

Introduction to MongoDB Realm

MongoDB Realm is a serverless platform that offers real-time synchronization, mobile-to-cloud data sync, serverless functions, and custom triggers, allowing developers to build highly interactive applications with minimal backend code. MongoDB Realm includes features such as:

  • Realm Sync for real-time data synchronization across devices.
  • Realm Database for offline-first capabilities.
  • Serverless Functions to execute backend logic without needing dedicated servers.
  • Triggers to automatically respond to data changes.

These features make MongoDB Realm ideal for applications requiring real-time data updates, such as collaborative tools, IoT applications, and mobile apps with offline support.


Key Features of MongoDB Realm

1. Real-Time Synchronization

Realm Sync ensures that data is automatically synchronized between devices and the backend database. This feature is invaluable for applications requiring real-time collaboration, as changes on one device are instantly reflected on others.

2. Offline-First Architecture

MongoDB Realm’s offline-first architecture allows users to continue using the app without an internet connection. Data is automatically synced once connectivity is restored, making it ideal for mobile applications.

3. Serverless Functions

Serverless functions in MongoDB Realm allow developers to define custom backend logic that can be executed in response to client requests, database events, or scheduled tasks, all without managing a dedicated server.

4. Triggers

Triggers in MongoDB Realm enable automated workflows by responding to changes in the database. For instance, you can configure triggers to notify users when new data is available or automatically process data as it’s added.


Setting Up MongoDB Realm

Step 1: Log In to MongoDB Atlas and Create a Realm App

  1. Visit your MongoDB Atlas dashboard and navigate to the Realm section.
  2. Click Create New App and select the project and cluster you want to use.
  3. Configure a Realm Sync application and enable the necessary permissions.

Step 2: Enable Realm Sync

  1. Under Realm Sync, select the sync configuration type—either Partition-Based Sync or Flexible Sync.
  2. Define the partition key if using Partition-Based Sync. This key determines how data is partitioned across devices.

Step 3: Define User Authentication

  1. In the Authentication tab, select the authentication providers you want to use (e.g., Email/Password, Anonymous, Google, Facebook).
  2. Set up authentication rules and configure each provider with necessary details.

Real-Time Data Synchronization

How Realm Sync Works

Realm Sync automatically synchronizes data between devices and MongoDB Atlas, allowing real-time data collaboration across multiple clients. You can configure it to sync only specific data partitions or allow more flexible data access.

Implementing Realm Sync

  1. Define a Partition Key in your MongoDB Realm configuration to enable partition-based synchronization.
  2. Set Up Permissions for data access based on user roles or fields.

Code Example: Setting Up Realm Sync in a Mobile App

In a mobile app (e.g., React Native), use the MongoDB Realm SDK to configure real-time synchronization.

javascript
import Realm from "realm";
import * as RealmWeb from "realm-web";

const app = new Realm.App({ id: "your-realm-app-id" });
const credentials = Realm.Credentials.anonymous();

async function loginAndSync() {
const user = await app.logIn(credentials);

const config = {
schema: [{ name: "Task", properties: { _id: "objectId", name: "string", status: "string" } }],
sync: { user, partitionValue: "myPartitionKey" }
};

const realm = await Realm.open(config);
console.log("Realm synced and opened:", realm.path);
}

loginAndSync();


Serverless Functions

Serverless functions enable you to run custom code in the cloud, triggered by requests from your app, scheduled events, or database changes. These functions are great for implementing backend logic, handling complex data processing, or integrating third-party APIs.

Creating a Serverless Function

  1. Go to the Functions section in the MongoDB Realm dashboard.
  2. Click Create New Function and provide a name.
  3. Write the function code directly in the Realm editor.

Example: A Serverless Function to Send Welcome Emails

javascript
exports = function({ email }) {
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(context.values.get("SENDGRID_API_KEY"));

const msg = {
to: email,
from: "[email protected]",
subject: "Welcome to Our App!",
text: "Thanks for joining our app. Let us know if you have any questions!"
};

sgMail.send(msg)
.then(() => console.log("Email sent to", email))
.catch((error) => console.error("Error sending email:", error));
};

In this example, the serverless function sends a welcome email to new users upon signup.


Custom Functions and Triggers

Using Triggers

Triggers enable real-time responses to data changes. MongoDB Realm supports Database Triggers (for data changes) and Authentication Triggers (for events like new user registration).

Setting Up a Trigger

  1. Go to the Triggers section in MongoDB Realm.
  2. Select Create Trigger and choose between Database or Authentication triggers.
  3. Define the conditions (e.g., on insert, update, or delete).
  4. Write custom code to execute when the trigger conditions are met.

Example: A Trigger to Track User Activity

Suppose you want to log each time a user updates their profile. Here’s how to create a database trigger:

  1. Create a Database Trigger on the UserProfile collection.
  2. Select Trigger Event as Update.
  3. In the function, add logic to log the activity.
javascript
exports = function(changeEvent) {
const { fullDocument } = changeEvent;
const activityLog = context.services.get("mongodb-atlas").db("myDB").collection("ActivityLog");

activityLog.insertOne({
userId: fullDocument._id,
activity: "Profile Update",
timestamp: new Date()
});
};


Sample Project: Real-Time Collaboration App with MongoDB Realm

For our sample project, let’s create a real-time collaboration app where users can create, edit, and view shared tasks in real-time. This app will leverage Realm Sync for live updates, serverless functions for backend logic, and triggers for logging user activities.

Project Structure

plaintext
realm-collab-app/

├── src/
│ ├── components/
│ │ └── TaskList.js
│ ├── services/
│ │ └── realmService.js
│ ├── App.js
└── package.json
  • src/services/realmService.js: Configures Realm Sync and database operations.
  • src/components/TaskList.js: Displays tasks and enables real-time updates.
  • App.js: Main app component, sets up navigation and context.

Step 1: Configure Realm Sync

In src/services/realmService.js, set up Realm Sync:

javascript
import Realm from "realm";
import * as RealmWeb from "realm-web";

const app = new Realm.App({ id: "your-realm-app-id" });
const credentials = Realm.Credentials.anonymous();

export const connectRealm = async () => {
const user = await app.logIn(credentials);

const config = {
schema: [{ name: "Task", properties: { _id: "objectId", name: "string", status: "string" } }],
sync: { user, partitionValue: "myPartitionKey" }
};

return await Realm.open(config);
};

Step 2: Create the Task List Component

In src/components/TaskList.js, create a component to display tasks in real-time.

javascript
import React, { useEffect, useState } from 'react';

const TaskList = ({ realm }) => {
const [tasks, setTasks] = useState([]);

useEffect(() => {
const tasksCollection = realm.objects("Task");
setTasks(tasksCollection);

tasksCollection.addListener(() => {
setTasks([...tasksCollection]);
});

return () => tasksCollection.removeAllListeners();
}, [realm]);

return (
<ul>
{tasks.map(task => (
<li key={task._id}>{task.name} - {task.status}</li>
))}
</ul>

);
};

export default TaskList;


Conclusion and Next Steps

MongoDB Realm streamlines the development of real-time, serverless applications with its powerful sync capabilities, serverless functions, and triggers. These features open the door for highly responsive and scalable applications, providing flexibility for modern development needs.

Next Steps:

  1. Integrate Realm Database for enhanced offline-first support in mobile apps.
  2. Explore Custom User Authentication for more secure access control.
  3. Experiment with Realm Triggers to automate complex workflows and data processing.

Stay tuned for the next blog, where we’ll dive deeper into advanced MongoDB Realm features like integrating with third-party APIs, building custom UI components, and managing permissions.