Navigation

Functions

➤ Functions are written in Javascript.
  • ECMAScript 6 features (e.g. const and let) are not supported.
  • Functions do not continue execution after returning. There are no event listeners or asynchronous callbacks.
  • Functions return values as BSON. See BSON for more information.
➤ Functions are written in the function editor and referenced by name.

Stitch functions run the Javascript function assigned to exports. All Stitch functions are required to assign a Javascript function to exports.

Stitch functions may be called from other Stitch functions or from the Javascript SDK.

Stitch functions may be called from other Stitch functions or from the Android SDK.

Stitch functions may be called from other Stitch functions or from the iOS SDK.

For example, assume the Stitch function named “increment” is defined as follows:

exports = function (arg) { return arg + 1; }

The Stitch function named “increment” can be called from another Stitch function as follows:

context.functions.execute("increment", 1); // returns 2

The Stitch function named “increment” can be called from the client SDK as follows:

stitchClient.executeFunction("increment", 1).then(/* ... */);
stitchClient.executeFunction("increment", 1).addOnCompleteListener(/* ... */);
stitchClient.executeFunction("increment", args: 1).response(/* ... */);
➤ Functions use context to access services and other contextual information.
  • Services like Twilio or GitHub can be accessed through context.services.
  • Functions can execute other functions using context.functions.
  • Information about the requesting user can be accessed through context.user.
  • Global variables can be defined in Stitch and referenced with context.values.

For more information see Function Context.

Example

The following example function queries the MongoDB service and sends a text message to each user.

exports = function(message){
    var mongodb = context.services.get("mongodb-atlas");
    var twilio = context.services.get("twilio");
    var coll = mongodb.db("db").collection("users");
    var users = coll.find();
    users.forEach(function(user){
       twilio.send({
           to: user.phone,
           from: context.values.get("twilioNumber"),
           body: message
       });
   });
}

Defining Functions

Use the following procedure to define a function in the MongoDB Stitch console:

  1. Select your MongoDB Stitch app in the console. If you haven’t yet created a MongoDB Stitch app, see Getting Started.

  2. Click Functions in the left navigation pane.

  3. Click New Function in the Functions view.

  4. Enter a name for the function in the Name field. The name must be unique within the MongoDB Stitch app where it is defined.

  5. You can specify any of the following function properties:

    Property Description
    Private If selected, the function may be called only from incoming webhooks, rules, and other functions defined in the MongoDB Stitch Admin console. Private functions may not be called from MongoDB Stitch client applications.
    Can Evaluate An expression in the format of a JSON document that must evaluate to true before the function may run. The expression can include expansions. An empty JSON document always evaluates to true, indicating that the function can always be run. This function-specific expression is evaluated before other service-specific rules. An expression is required when Skip Rules is enabled for the function.
  6. Write the function code.

  7. Click Done.

  8. Click Save to save the function.

Function Context

The context variable contains the following.

Property Description
context.services Access to functions provided by Services.
context.values Access to variables defined in the Stitch console. See Values.
context.user Information about the requesting user, including the type of authorization.
context.functions Access to execute other functions.

For more information see Function Context.

Calling Other Functions

To call a separate function from within a function, use context.functions. Suppose the function sum is defined as follows:

exports = function (a, b) { return a + b; }

This can be called from another function difference as follows:

exports = function(a, b) {
    return context.functions.execute("sum", a, -1 * b);
}

Return Values

Functions return values as extended JSON. Consider the following function named return_something.

return {a : 1, b: false, c: "hello"};

Calling return_something from the client SDK receives the result as extended JSON.

stitchClient.executeFunction("return_something").then(
function(result) {
   console.log(JSON.stringify(result));
   // prints { a: { $numberDouble: 1 }, b: false, c: "hello" }
})

Services

Services have easy-to-use functions which interact with their APIs. For more information see Services. For a complete reference on available service functions see the APIs.

Service Description Basic Example
MongoDB Atlas Interact with a MongoDB database.
exports = function() {
    var db = context.services.get("mongodb-atlas").db("db");
    var collection = db.collection("coll");
    return collection.findOne({});
}
Amazon S3 Store data.
exports = function() {
    var s3 = context.services.get("s3");
    s3.put({
       "content": "Hello world!",
       "contentType": "text/plain",
       "acl": "public-read",
       "bucket": "my-bucket-name",
       "key": "test-object"
    });
}
Amazon SES Send email.
exports = function() {
    var ses = context.services.get("ses");
    var from = "no-reply@example.com";
    var to = "email@example.com";
    var body = "Hello world!";
    ses.send(from, to, "", body);
}
HTTP Make HTTP requests.
exports = function() {
    var http = context.services.get("http");
    return http.get({url: "http://google.com"});
}
Twilio Send and receive text messages.
exports = function() {
    var twilio = context.services.get("twilio");
    twilio.send({
        number: "+15558901234",
        from: context.values.get("twilioNumber"),
        body: "Hello world!"
    });
}

Clients

You can call the function from your application client to execute the function.

To execute a function, use the StitchClient.executeFunction() method, passing the function name and arguments.

For example, suppose the function sum is defined in Stitch as follows:

exports = function(a, b) { return a + b; }

It can be called from the client as follows:

stitchClient.executeFunction("sum", 3, 4).then( /* ... */ );

To execute a function, use the StitchClient.executeFunction() method.

For example, suppose the function sum is defined in Stitch as follows:

exports = function(a, b) { return a + b; }

It can be called from the client as follows:

stitchClient.executeFunction("sum", 3, 4).addOnCompleteListener( /* ... */ );

To execute a function, use the StitchClient.executeFunction() method, passing the function name and arguments.

For example, suppose the function sum is defined in Stitch as follows:

exports = function(a, b) { return a + b; }

It can be called from the client as follows:

stitchClient.executeFunction("sum", args: 3, 4).then( /* ... */ );

The Debug Console

The MongoDB Stitch console provides a facility for testing functions. You can reach the Debug Console through the Stitch left-side navigation.

To use the Debug Console for testing functions, select an application user for the function to run as at the top of the screen, then write the function code with the form inputs.

Examples

Returning Documents

A very simple function is one which returns an array of documents.

return [
   { "type": "apples", "qty": 25 },
   { "type": "oranges", "qty": 50 }
]

The above function returns the following to the client:

[
  {
    "type": "apples",
    "qty": {
      "$numberDouble": "25"
    }
  },
  {
    "type": "oranges",
    "qty": {
      "$numberDouble": "50"
    }
  }
]

The MongoDB Service

In order to use the MongoDB service in a function stage, you must have rules set up for each namespace included in the operation.

The following example uses a collection called cars in a database called vehicles, with the following documents:

{ "_id": 1, "make": "Honda", "model": "Accord", "doors": 4 }
{ "_id": 2, "make": "Ford", "model": "Mustang", "doors": 2 }
{ "_id": 3, "make": "Toyota", "model": "Camry", "doors": 4 }

The following function finds 2-door cars, and returns only the make and model fields.

exports = function() {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("vehicles").collection("cars");
    return coll.find({"doors": 2}, { "make": 1, "model": 1});
}

The above function returns the following array to the client:

[
  {
    "make": "Ford",
    "model": "Mustang"
  }
]

S3 Service

One use case for a MongoDB Stitch application is to allow users to upload binary data to an Amazon S3 bucket. You can accomplish this in a function using the S3 service.

The following example takes a hex-encoded bytes and uses the put function to upload it to an S3 bucket.

exports = function() {
    var s3 = context.services.get("s3");
    var binary = Uint8Array.from([0x68, 0x65, 0x6c, 0x6c, 0x6f])
    s3.put({
       "content": binary,
       "contentType": "text/plain",
       "acl": "public-read",
       "bucket": "my-bucket-name",
       "key": "test-object"
    })
}

The document returned to the client has the following form:

{ "location": "https://my-bucket-name.s3-us-west-2.amazonaws.com/test-object" }

Note

In the above example, the key argument to the S3 service represents the path to the object in the S3 bucket, relative to server root. It must not begin with /.

The Twilio Service

The following example uses a MongoDB database called people and a collection called users with the following documents:

{ "_id" : 1, "name" : "Amos", "city" : "Boston", "phone" : "+15558907614" }
{ "_id" : 2, "name" : "Barbara", "city" : "Atlanta", "phone" : "+15558340186" }
{ "_id" : 3, "name" : "Chet", "city" : "Boston", "phone" : "+15553528799" }

The following function combines a find call to a MongoDB service with a send call to a Twilio service. It sends a text message to all the users who meet the specified criteria.

exports = function() {
    var atlas = context.services.get("mongodb-atlas");
    var coll = atlas.db("people").collection("users");
    var twilio = context.services.get("twilio");
    var docs = coll.find({"city": "Boston"}, {});
    docs.forEach(function(document){
        twilio.send({
            number: document.phone,
            from: context.values.get("twilioNumber"),
            body: "Looks like rain today. Bring and umbrella!"
        });
    });
}

The two users from Boston receive a text message via Twilio. A successful function response returns an empty array to the client.