Call a Function

MongoDB Realm Functions allow you to run serverless snippets of code. MongoDB Realm Functions are useful for abstracting away implementation details from client applications by doing things such as reusing code-snippets to process data or dynamically performing actions based on the current user, processing data, and more. You can call MongoDB Realm Functions from the client SDK. The active user of a given MongoDB Realm Function execution is the authenticated user that called it.

In the Node SDK you call functions as a logged in user with the User.functions interface. There are two ways to call a function:

  • You can call a function as if was a method defined locally on the User.functions interface.
  • You can call the User.functions.callFunction() method to call a function by providing its stringified name and a list of arguments.
Info With Circle IconCreated with Sketch.Note
Link a MongoDB Atlas Data Source

This example requires a MongoDB Realm Application with a linked Atlas data source. Replace the "<appId>" in the code block with your app id, available in the lefthand corner of the MongoDB Realm UI.

const Realm = require("realm");
const appId = "<appId>"; // Set Realm app ID here.
const appConfig = {
id: appId,
timeout: 10000,
async function run() {
let user;
try {
const app = new Realm.App(appConfig);
const credentials = Realm.Credentials.anonymous();
user = await app.logIn(credentials);
const numA = 2;
const numB = 3;
const myArgs = [numA, numB];
const result = await user.functions.sum(numA, numB);
const resultOfCallFunction = await user.callFunction("sum", myArgs); // alternate syntax to call a MongoDB Realm Function
console.log(`Using the "functions.sum()" method: the sum of ${numA} + ${numB} = ${result}`);
console.log(`Using the "callFunction()" method: the sum of ${numA} + ${numB} = ${resultOfCallFunction}`);
} finally {

When you run the code sample, your output should resemble the following:

Using the "functions.sum()" method: the sum of 2 + 3 = 5
Using the "callFunction()" method: the sum of 2 + 3 = 5
Give Feedback