Navigation

Function Utilities

For developer convenience, MongoDB Stitch functions have access to utility functions provided through various global variables.

  • console can be used to output to the debug console and console logs.
  • JSON can be used to convert between string and object representations of standard JSON.
  • EJSON can be used to convert between string and object representations of MongoDB Extended JSON.
  • BSON can be used to construct and manipulate BSON types.
  • utils.crypto provides methods for working with cryptographic algorithms.

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 a warning to the console log. It accepts variadic arguments which are all included in the log output.

console.error(arg...)

Logs an error 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.

JSON

The JSON variable provides functions for converting between standard JSON and Javascript objects. This is a standard built-in object across most Javascript environments and is documented here.

EJSON

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

Note

To avoid ambiguity with the $regex EJSON type, queries with the $regex operator must use a BSON.BSONRegExp. See Finding Documents Matching a Regular Expression for an example.

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

utils.crypto

The crypto utility provides methods for working with cryptographic algorithms.

utils.crypto.hmac(input, secret, hash_function, output_format)

Generates an HMAC signature from the provided input and secret. This is useful when communicating with third-party HTTP services that require signed requests.

Parameter Type Description
input string The input for which you would like to generate a signature.
secret string The secret key to use when generating the signature.
hash_function string The name of the hashing function to use when generating the signature. The following functions are supported: "sha1", "sha256", "sha512".
output_format string The format of the generated signature. Can be either "hex" for a hex string, or "base64" for a Base64 string.
Returns:The signature of the input, in the format specified by output_format.
utils.crypto.hash(hash_function, input)

Generates a hash value for the provided input using the specified hash function.

Parameter Type Description
hash_function string The name of the hashing function. The following functions are supported: "sha1", "sha256", "md5".
input string or BSON.Binary Required. The input for which you would like to generate a hash value.
Returns:A hash value for the provided input generated by the specified hashing function.

Example

The API for Coinbase allows developers to make HTTP requests on behalf of their account by using an API key and by signing the requests with a secret. This page on their documentation gives an overview of the mechanics.

The following example shows a function using utils.crypto.hmac to sign a request to the Coinbase API. The function requests a list of transactions from the primary wallet of the user associated with the API key and secret.

Note

This function assumes the existence of an HTTP service named coinbase with a rule that allows GET requests to api.coinbase.com. It also assumes the existence of values named coinbase_api_key and coinbase_secret that are populated appropriately.

The API key configured in Coinbase must also allow the wallet:transactions:read scope for the request to complete successfully with a 200 OK status.

exports = function() {
  const cur_unix_time = Math.floor(Date.now() / 1000);
  const api_url = "https://api.coinbase.com";
  const request_path = "/v2/accounts/primary/transactions";

  const message = cur_unix_time.toString() + "GET" + request_path;
  const signature = utils.crypto.hmac(message, context.values.get("coinbase_secret"), "sha256", "hex");

  const coinbase = context.services.get("coinbase")
  const response = await coinbase.get({
    url: api_url + request_path,
    headers: {
      "CB-ACCESS-SIGN": [signature],
      "CB-ACCESS-TIMESTAMP": [cur_unix_time.toString()],
      "CB-ACCESS-KEY": [context.values.get("coinbase_api_key")]
    }
  });

  return EJSON.parse(response.body.text());
};