MongoDB Stitch Tutorial

I have talked about MongoDB‘s Backend as a Service (BaaS) Stitch previously. In this post, let’s take a look at a basic Stitch application and how easy it is to get started. For this particular tutorial, we’ll be looking at basic Stitch functionality. However, I’ll point out some options along the way for extending the application.

The Stitch Application Overview

For this tutorial, let’s imagine an application that tracks blood glucose for diabetic patients. A blood sugar monitor, like the One Drop Chrome, would send results to our application. Medical practitioners could see the results and leave comments on the reading. While beyond the scope of this tutorial, Stitch can integrate with a service such as Twilio to send the comments via SMS message to the patient for diabetic management suggestions. From a development perspective, this can be integrated with MongoDB 3.6 Change Streams as well.

A sample application page is available to view here with working comments attached to a MongoDB Atlas cluster and using Stitch. Let’s see how it was generated.

Cloud Services

Stitch runs on top of Atlas so we’ll need to set those services up.


First off we’ll need to log into MongoDB Atlas or create an account. Then we’ll need to set up an Atlas Cluster. There is an option for an M0 level which is free and doesn’t require a credit card to get started. This is a great feature to be able to try out this incredible service.

Stitch is currently only located in the AWS US East 1 region so it is best to set your cluster up in that region for optimal performance. Once the cluster is configured, deployed, and initialized we’ll move onto setting up Stitch.


To get started setting up a Stitch application, in the MongoDB Atlas console, select the Stitch App option.

Stitch Application Selection

Then the Create New Application button in the upper right. Give the application a name, I’m calling this application glucose, and select the MongoDB Atlas Cluster you want to connect to.

New Stitch App

It will take a minute to spin up the new application. Once it is up and running, we’ll want to set authentication to Anonymous Authentication.

Anonymous Authentication

There are a few pieces of information we’ll need from this screen for our application. For this tutorial, we’ll be using the information from JS(Browser) but it is great to see support for Node.js, iOS, and Android configurations as well.

Stitch client setting strings

We’ll want to grab the <script> information from the Importing on a Webpage bit and add that to our HTML that we’ll generate. But first, let’s setup our database and collection. We’ll want to click mongodb-atlas from the left navigation panel and then the Rules tab.

Connect the Database

Click NEW to add a new MongoDB collection. For the database, I’ve called mine glucose and I called the collection results. Now we’ll need to configure some permissions to allow, for the purposes of this tutorial, anyone to read the comments. Obviously, with sensitive and private medical data we would want to set the permissions to be more strict.

Under the Rules tab, click on the collection you just created and proceed to the Filters tab.

Delete this existing filter and click SAVE. Now head on over to the Field Rules tab. In the Permissions for top-level document section, we’ll want to change the Read rule to {} and click SAVE.

With these settings, we are allowing anyone to read any records in glucose.results, but only the owners can edit or delete their own comments. Stitch has integration with services such as Facebook and Google via OAuth. Further, custom authentication is possible with JSON Web Tokens.

Stitch the Application to the HTML

Now that we’ve set up our Stitch application on the backend, we need to integrate it into our HTML page. For this tutorial, we’re generating a static page with fake data. However, in a real application, we would use some dynamic content. At any rate, let’s see how we can proceed.


We’ll generate a basic HTML page with our <script> information in the <head> section. And we’ll include a form at the end to be able to get input from our medical professionals.

<!doctype html>
<html lang="en">
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie-edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Blood Glucose</title>
        <script src=""></script>
        <h2>Sample Blood Glucose Report</h2>
            <p>Patient Id: 12345</p>
            <p>Date: 5 November 2017</p>
            <p>Time: 07:23am</p>
            <p>Reading was taken: Before Breakfast</p>
            <p>Result: 110</p>
            <div id="comments">
                <label for="new_comment">Add Comments:</label>
                <input id="new_comment">
                <input class="button" type="submit">

Let’s also think about what we’re trying to do with our JavaScript and add in the appropriate hooks in our HTML before we tackle our JavaScript.

Since we want our comments to load when the page does, let’s add an onload to the <body> tag:

<body onload="displayCommentsOnLoad()">

We’ll also need to add an on click listener to our form:

<input class="button" type="submit" onClick="addComment()">

Nice. It seems like, then, that we have three JavaScript functions to write to get our functionality implemented. The two mentioned and a third displayComments seems like it will be necessary. Let’s tackle those functions next in glucose.js.



const client = new stitch.StitchClient('glucose-XXXXX');
const db = client.service('mongodb', 'mongodb-atlas').db('glucose');

function displayCommentsOnLoad() {

function displayComments() {
    db.collection('results').find({}).then(docs => {
        const html = => "<div>" + c.comment + "</div>").join("");
        document.getElementByID("comments").innerHTML = html;

function addComment() {
    const foo = document.getElementById("new_comment");
    db.collection("results").insert({owner_id : client.authedId(), comment : foo.value}).then(displayComments);
    foo.value = "";

You’ll want to alter the glucose-XXXXX to utilize the App Id for your own application and if you are using a different database and/or collection names, make those changes as well.

We’ll also need to add the script to our HTML in the <head> section:

<script src="glucose.js"></script>

I have the completed project code, with some minimal Foundation styling available on GitHub as well.

Wrap Up

And that’s it! Neat. We now have a basic web page that will accept comments from a user (medical professional) and, through the power of Stitch, save the comments in MongoDB Atlas hosted database. Stitch has provided the backend power and we just had to write some minimal JavaScript functions to handle the button click and document insert into our collection.

Follow me on Twitter @kenwalger to get the latest updates on my postings. Or better yet, sign up for the email list to get updates in your mailbox!

There are a few MongoDB specific terms in this post. I created a MongoDB Dictionary skill for the Amazon Echo line of products. Check it out and you can say “Alexa, ask MongoDB for the definition of a document?” and get a helpful response.


Overview of MongoDB’s BaaS offering: MongoDB Stitch

One of the challenges many developers have is keeping up with backend processes. Things like data security, service integrations, and code for data manipulations can take up a lot of time and resources. As a result, many have made a move to utilize a Backend as a Service (BaaS). If you have an application backed by MongoDB there is a new Baas option available, MongoDB Stitch.

MongoDB allows you to get started at no cost with Stitch, which is always great. At the moment it is backed by MongoDB’s Database as a Service (DBaaS) offering, Atlas. In another post, I discussed Atlas and am excited that these two services are connected.

BaaS Overview

A Backend as a Service approach to development allows mobile and web developers to connect their applications to backend cloud storage and utilize inherent processing capabilities. Further, it provides many common features that users demand from sites and applications. Some of these features are security, user management, push notifications, and social networking integrations.

MongoDB Stitch Benefits

Stitch provides many capabilities for developers to leverage the features inherent in MongoDB along with BaaS concepts. It provides direct access to the database, whether it is already existing or new data, Stitch allows developers to focus on building their application. The backend logic is taken care of and provided. This leads to a faster development cycle.

Stitch takes MongoDB’s data security features even further. It provides functionality such as end user authentication and access control on a per-field basis. For example, if the marketing department doesn’t need access to a customer’s financial information, those fields can be excluded from their access rights. This allows developers and application stakeholders to have confidence that information and services are only available to the proper users.

MongoDB has built Stitch in an open fashion. It provides a single API allowing access to both the MongoDB database as well as other public cloud services. This allows for microservice integration and prevents being committed to a single vendor.

Another terrific benefit is the integration with Atlas. This allows for easy scaling of capacity and performance as an application grows. This is yet another set of duties that don’t need to be managed ourselves. We can allow the details of the backend application and infrastructure to be handled by a team of Dev-Ops folks at MongoDB and can then concentrate on the application itself.

MongoDB Stitch Components

There are three main components of Stitch, pipelines, services, and rules. Services come in two different varieties, MongoDB services, and partner services for integration with services like Amazon S3 or Twilio for messaging. Let’s take a quick look at what these different components do and how they fit into an application.


Services in Stitch allow for application integration and execution of common actions. There are integrations for a variety of third-party (partner) services for such tasks as user authentication through Facebook or Google, Slack, Twilio, and some components of AWS, to name a few. The HTTP Service allows for a MongoDB Stitch application to connect to REST API services. MongoDB has a dedicated service for connecting to Atlas and has some built in pipeline operations.


A Stitch pipeline allows for a sequence of actions to be performed in order by the Stitch services. This is a powerful feature. It allows a series of actions to be defined all through simple JSON syntax.

A pipeline is built in stages, each running in consecutive order. A stage runs and passes the information it generates onto the next stage. For example, you can do a MongoDB aggregation stage from your data and determine which user in the past week had the most likes on your new Snap-o-gram app. That stage could then pass that information to the Twilio Service which could send a text to their phone with this awesome accomplishment.

There are some Built-In Actions for filtering the pipeline input, defining in an explicit way what the output of a stage will be, expression evaluation against input documents, and a project feature, to name a few. Another nice feature MongoDB has provided is the concept of named pipelines. This allows for a designed pipeline to be reused within a Stitch app and referenced by name. A tremendous help for writing code that follows the DRY (don’t repeat yourself) principle.


The last major component of a MongoDB Stitch is Rules. Rules, as one might guess, allow for a control over the actions a service takes. Rules are designed and written in JSON format, as are pipelines.

One can define a rule for read, write, and validation operations, for example. These can be used at the document level and on down to the field level. Want to prevent a service from reading specific financial data in a document? Write a rule for that. It is a powerful feature of MongoDB Stitch and provides an extra level of security for your data.

MongoDB Stitch Development

Right now there are three different options for developing a Stitch application. Using JavaScript for web applications and for mobile development there are options for Android and iOS. MongoDB has put together some great tutorials and getting started guides.

Wrap Up

The name Stitch comes out of the idea of stitching together the pieces of an application and not from the Disney character in Lilo & Stitch. Given the benefits and features MongoDB Stitch brings to the table, I think it is a very appropriate name. Much like sewing brings all of the pieces of a garment together, MongoDB Stitch does the same thing for your application.

I know that for myself I plan on utilizing this service on my next project.

As with any “pre-packaged” service, one gives up some flexibility and control over your application. However, for being able to retain direct access to your MongoDB database, and the collections and documents it contains, Stitch is a great option. Keep in mind that as of this post, Stitch is still in a beta version. As with any beta product, things may change with the final product.

There are several MongoDB specific terms in this post. I created a MongoDB Dictionary skill for the Amazon Echo line of products. Check it out and you can say “Alexa, ask MongoDB for the definition of authentication?” and get a helpful response.

Follow me on Twitter @kenwalger to get the latest updates on my postings.