Navigation

Trigger Snippets

Overview

This page demonstrates how to use Realm Triggers and Realm Functions within MongoDB Realm to implement common patterns.

Database Triggers

The code snippets in this section cover common use cases for database Triggers. All of the snippets require a linked MongoDB cluster.

Send an SMS On New Document Inserts

This trigger Function sends an SMS message to a pre-defined phone number whenever a new document is inserted into a collection using the twilio.send() action.

exports = function(dbEvent) {
  // Only run if this event is for a newly inserted document
  if(dbEvent.operationType !== "INSERT") { return }

  // Format a message with the inserted document's `title` field.
  const { title } = dbEvent.fullDocument;
  const msg = `New document was inserted with title: ${title}`;

  // Get the Twilio messaging service number and the number that
  // should receive the SMS from stored global values.
  const fromPhone = context.values.get("twilioPhoneNumber");
  const toPhone = context.values.get("myPhoneNumber");

  // Get a Twilio service client. The service rules should allow you
  // to call the `send` action when the `to` phone number matches your
  // pre-defined number.
  const twilio = context.services.get("myTwilio");

  // Send the SMS Message
  twilio.send({ To: toPhone, From: fromPhone, Body: msg });
};

Send an SMS When a Specific Field Changes

This trigger function sends an SMS message to a pre-defined phone number whenever a specific field is updated in a collection’s documents using the twilio.send() action.

exports = function(dbEvent){
  // Only run if this event is for an updated or replaced document
  if (dbEvent.operationType !== "INSERT" || dbEvent.operationType !== "REPLACE") { return }

  // Get an array that contains the names of any updated fields
  const { updateDescription } = dbEvent;
  const updatedFields = Object.keys(updateDescription.updatedFields);

  // Check if a specific field (specific by the value of `fieldName`) was updated.
  const fieldName = "someField"
  const fieldRegex = new RegExp(fieldName);
  const fieldWasUpdated = updatedFields.some(
    field => fieldRegex.test(field)
  );

  if (fieldWasUpdated) {
    // Format a message with the updated field's value.
    const fieldValue = dbEvent.fullDocument[fieldName];
    const msg = `The field ${fieldName} was updated to have value: ${fieldValue}`;

    // Get the Twilio messaging service number and the number that
    // should receive the SMS from stored global values.
    const toPhone = context.values.get("myPhoneNumber");
    const fromPhone = context.values.get("twilioPhoneNumber");

    // Get a Twilio service client. The service rules should allow you
    // to call the `send` action when the `to` phone number matches your
    // pre-defined number.
    const twilio = context.services.get("myTwilio");

    // Send the SMS Message
    twilio.send({ To: toPhone, From: fromPhone, Body: msg });
  }
};

Authentication Triggers

The code snippets in this section cover common use cases for authentication Triggers. All of the snippets require you to have enabled one or more authentication providers.

Authentication Trigger Snippets

Store New Users in MongoDB

This trigger Function automatically inserts a document into MongoDB that models new application users.

exports = function(authEvent){
  // Only run if this event is for a newly created user.
  if (authEvent.operationType !== "CREATE") { return }

  // Get the internal `user` document
  const { user } = authEvent;

  const users = context.services.get("mongodb-atlas")
    .db("myApplication")
    .collection("users");

  const isLinkedUser = user.identities.length > 1;

  if(isLinkedUser) {
    const { identities } = user;
    return users.updateOne(
      { id: user.id },
      { $set: { identities } }
    )

  } else {
    return users.insertOne({ _id: user.id, ...user })
     .catch(console.error)
  }
};