Serverless and Functions as a Service are relatively new development paradigms that are gaining in popularity. Let’s take a quick look at what MongoDB Stitch offers in this space.

Ilya Pavlov / Unsplash

Functions in Stitch are written in JavaScript ECMAScript and can be called from others scripts in Stitch, or from external JavaScript leveraging the client SDK.

Here’s an example of a function in Stitch:

exports = function(message) {

  const mongodb = context.services.get("mongodb-atlas");

  const coll = mongodb.db("db").collection("users");

  const twilio = context.services.get("my-twilio-service");

  const yourTwilioNumber = context.values.get("twilioNumber");

  coll.find().toArray().then(users => {

    users.forEach(user => twilio.send({

      to: user.phone,

      from: yourTwilioNumber,

      body: message

    })

  );

});

A few things might stand out about the structure and content of this script. Let’s take a closer look at some of these components.

The first thing you’ll notice is exports. All Stitch functions run the JavaScript function assigned to the global variable exports. This is similar in theory and practice to the Node.js module.exports object.

Next, you’re likely to see references to context. Access to resources from within Stitch scripts is facilitated through the use of a context object. This object has several elements:

Notice how easily I’m able to begin accessing my database, and collection.

Lastly, a resource available to developers of serverless functions in Stitch that we’re not representing in the example function, but that bears mentioning is the set of utilities exposed as methods in Stitch functions. There are several pre-imported JavaScript libraries available for your serverless functions:

Utilities and context objects leveraged as a part of your application make it possible to create rich, powerfully integrated applications that don’t need a lot of the boilerplate code set up.

Developing applications leveraging serverless is a bit different — but once you get used to leveraging the tools available, it is extremely powerful and helps you create better applications. And do it faster as well. It’s a huge benefit to using MongoDB Stitch in your development cycle.

To read more, and get started, check out the documentation, sign up for a free Atlas account and begin writing a serverless application today.