Navigation

Function Context

MongoDB Stitch functions can interact with connected services, user information, predefined values, and other functions through the context variable.

  • 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.
  • Information about the HTTP request that triggered a function call can be accessed through context.request.
  • Global variables can be defined in Stitch and referenced with context.values.

MongoDB Stitch functions can use console to output to the console log.

MongoDB Stitch functions can use EJSON to convert between string and object representations of MongoDB Extended JSON.

context.services

Integrated Services are accessible in functions using context.services.

context.services.get(serviceName)

Returns a service handle object or undefined if no such service exists.

Parameter Type Description
serviceName string The name of the service. This is the name you provided for the service when it was created. For the MongoDB Atlas service, the name is always mongodb-atlas, and for the Push Notification service, the name is always gcm.
Returns:An object with methods to perform service actions. See Functions for a reference of available actions on each service. If the service does not exist, undefined is returned.

Example

When creating a MongoDB Stitch app through Atlas, a default MongoDB service is added and named “mongodb-atlas”.

exports = function() {
   var mongodb = context.services.get("mongodb-atlas");
   return mongodb.db("db").collection("coll").findOne();
};

See also

MongoDB (Atlas).

context.functions

Other functions defined in MongoDB Stitch may be called using context.functions.

context.functions.execute(functionName, arg...)

Calls another function defined in MongoDB Stitch.

Parameter Type Description
functionName string The name of the function.
arg mixed A variadic list of arguments passed to the function.
Returns:The returned value of the called function.

Example

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);
};

context.values

Provides access to constant values defined in MongoDB Stitch.

context.values.get(valueName)

Calls another function defined in MongoDB Stitch.

Parameter Type Description
valueName string The name of the defined value.
Returns:The value associated with the name or undefined if there is no value defined with name valueName.

Example

Define a value named incrementValue and set the value to 5.

Create a new function named increment with the following code:

exports = function (arg) { return arg + context.values.get("incrementValue"); };

context.user

Provides a view of the currently authenticated user. context.user is a document summarized as follows:

{
    "id": <string>,
    "type": <string>,
    "data": <document>,
    "identities": <array>
}

Example

The following is an example context.user document:

{
    "id": "5a09f135b6fc810f19421c12",
    "type": "server",
    "data": {
        "name": "api-key"
    },
    "identities": [
        {
            "id": "5a09f135b6fc810f19421c13",
            "provider_type": "api-key"
        }
    ]
}

context.request

Provides information about the external HTTP request that triggered the function call, which can help you determine the origin of the call. It may contain the following fields:

{
   "remoteIpAddress": <string>,
   "httpReferrer": <string>,
   "httpUserAgent": <string>
}

If there is no referrer header or user agent header present in the request, the respective field will be omitted.

Example

The following is an example context.request document:

{
   "remoteIpAddress": "54.173.82.137",
   "httpReferrer": "https://myapp.example.com/",
   "httpUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
}

console

console.log(arg...)

Logs information to the console log. It accepts variadic arguments which are all included in the log output.

console.warn(arg...)

Logs an error to the console log. It accepts variadic arguments which are all included in the log output.

console.err(arg...)

Logs a warning to the console log. It accepts variadic arguments which are all included in the log output.

Example

exports = function() {
    console.log("hello", "world");
};

After calling the above function, the log output can be seen by going to the console and clicking Logs.

EJSON

The EJSON variable provides functions for converting between MongoDB Extended JSON and Javascript objects.

EJSON.parse(extendedJsonString)

Attempts to parse the argument as MongoDB Extended JSON and returns the Javascript object representation if valid. If extendedJsonString is not valid JSON an exception will be thrown.

Parameter Type Description
extendedJsonString string A string representing serialized extended JSON.
Returns:A Javascript object representation of the extended JSON. The resulting Javascript object may contain BSON types.
EJSON.stringify(obj)

Serializes the Javascript object obj into MongoDB Extended JSON and returns the resulting string.

Parameter Type Description
obj document A Javascript object which may contain BSON types.
Returns:A string representation of the Javascript object.

BSON

BSON provides functions for constructing and manipulating BSON types.

Creating Explicit BSON types

The BSON global can be used to construct explicit BSON types. The following are the available BSON types in MongoDB Stitch:

Type Description Example
BSON.Binary A string of bytes. BSON.Binary.fromHex("a5f8c1", 0);
BSON.Code Embedded Javascript code. BSON.Code("var x = 123;");
BSON.DBPointer (Deprecated) A reference to another document. BSON.DBPointer("db.coll", BSON.ObjectId("5a14179d01236a9fc1086df6"));
BSON.DBRef A reference to another document. BSON.DBRef("db.coll", BSON.ObjectId("5a14179d01236a9fc1086df6"));
BSON.Decimal128 A 128 bit decimal. BSON.Decimal128.fromString("1.23");
BSON.Double A 64 bit double. BSON.Double(1.23);
BSON.Int32 A 32 bit signed integer. BSON.Int32(123);
BSON.Long A 64 bit signed integer. BSON.Long(0x00000000, 0x40000000);
BSON.MaxKey A value that compares higher than all other BSON values. BSON.MaxKey;
BSON.MinKey A value that compares lower than all other BSON values. BSON.MinKey;
BSON.ObjectId A 12 byte object ID. BSON.ObjectId("5a14179d01236a9fc1086df6");
BSON.BSONRegExp A regular expression. BSON.BSONRegExp("^test*", "i");
BSON.Symbol (Deprecated) A symbol. BSON.Symbol("symbol");
BSON.Timestamp Contains a 32 bit timestamp and 32 bit counter. For working with dates use Date. BSON.Timestamp(1511266261367, 0);

More information about BSON types can be found on BSON Types.

BSON.Binary

BSON.Binary has the following methods.

BSON.Binary.fromHex(hexString, subType)

Constructs a BSON.Binary from data represented as a hexadecimal string.

Parameter Type Description
hexString string A string of hexadecimal characters (0-9 and A-F). This must be byte aligned or an exception is thrown.
subType integer An integer in the range of 0-255. The value 0 represents generic binary. Other sub-types are documented on the BSON spec.
Returns:A BSON.Binary.
BSON.Binary.toHex()

Returns the BSON.Binary data represented as a hexadecimal string.

Returns:A string.
BSON.Binary.fromBase64(base64String, subType)

Constructs a BSON.Binary from data represented as a base64 string.

Parameter Type Description
base64String string A string of base64 encoded characters.
subType integer An integer in the range 0-255. The value 0 represents generic binary. Other sub-types are documented on the BSON spec.
Returns:A BSON.Binary.
BSON.Binary.toBase64()

Returns the BSON.Binary data represented as a base64 string.

Returns:A string.
BSON.Binary.text()

Returns a string representation of the data as UTF-8 encoded characters.

Returns:A string.

BSON.Decimal128

BSON.Decimal128.fromString(decimalString)

Constructs a BSON.Decimal128 from a string representation of a decimal number.

Parameter Type Description
decimalString string A string representing a decimal number. E.g. “123.45”.
Returns:A BSON.Decimal128.

BSON.Long

A BSON.Long is a 64 bit signed integer.

BSON.Long(low32, high32)

Constructs a BSON.Long from two 32 bit integers representing the low 32 bits and the high 32 bits.

Parameter Type Description
low32 integer Optional. Represents the low 32 bits of the BSON.Long.
high32 integer Optional. Represents the high 32 bits of the BSON.Long.
Returns:A BSON.Long. If no arguments are supplied the value returned is 0.

Examples

BSON can be used to return explicit BSON types.

exports = function() {
   return {
      a: BSON.Long(10),
      b: BSON.ObjectId("5a14179d01236a9fc1086df6"),
      c: BSON.Code("var x = 1"),
      d: new Date()
   };
};