MongoDB Stitch Tutorial
Tags: javascript, mongodb, stitch
Published: 2017-11-15 16:48:00

---
title: "MongoDB Stitch Tutorial"
published: true
tags: JavaScript,MongoDB,Stitch
canonical_url: https://www.kenwalger.com/blog/nosql/mongodb/mongodb-stitch-tutorial/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/cquqrko87x9mad4y8tbv.png
---

I have talked about [MongoDB](https://www.mongodb.com)‘s Backend as a Service (BaaS) Stitch [previously](https://www.kenwalger.com/blog/nosql/mongodb/mongodbs-baas-offering-stitch/). 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](https://www.kenwalger.com/blog/nosql/mongodb/flask-blood-glucose-tracker/) for [diabetic patients](https://www.amazon.com/gp/product/0470178116/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0470178116&linkCode=as2&tag=kenwalgersite-20&linkId=6d2f297c507bd99bca135dd52fc33e60) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=0470178116). A blood sugar monitor, like the [One Drop Chrome](https://www.amazon.com/gp/product/B06WWBFRVL/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B06WWBFRVL&linkCode=as2&tag=kenwalgersite-20&linkId=1a3970fd7847b18e062083d1f5c6f0e2) ![](https://www.kenwalger.com/blog//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&l=am2&o=1&a=B06WWBFRVL),&nbsp;would send results to our application. [Medical practitioners](https://en.wikipedia.org/wiki/Endocrinology) 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](https://www.twilio.com) 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](https://dev.to/kenwalger/change-streams-coming-soon-in-mongodb-36-967) as well.

A sample application page is available to view [here](https://kenwalger.com/stitch/glucose.html) with working comments attached to a [MongoDB Atlas](https://www.kenwalger.com/blog/nosql/mongodb/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.

###### Atlas

First off we’ll need to [log into](https://cloud.mongodb.com/user?nds=true#/login?nds=true) MongoDB Atlas&nbsp;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.

###### Stitch

To get started setting up a Stitch application, in the MongoDB Atlas console, select the&nbsp;_Stitch App_ option.

![Stitch Application Selection](https://i1.wp.com/www.kenwalger.com/blog/wp-content/uploads/2017/11/stitch_app_selection.png?resize=179%2C300&ssl=1)

Then the&nbsp;_Create New Application_ button in the upper right. Give the application a name, I’m calling this application&nbsp; **glucose** , and select the MongoDB Atlas Cluster you want to connect to.

![New Stitch App](https://i1.wp.com/www.kenwalger.com/blog/wp-content/uploads/2017/11/new_stitch_application-1.png?resize=300%2C298&ssl=1)

It will take a minute to spin up the new application. Once it is up and running, we’ll want to set authentication to&nbsp;_Anonymous Authentication_.

![Anonymous Authentication](https://i2.wp.com/www.kenwalger.com/blog/wp-content/uploads/2017/11/anon_auth.png?resize=300%2C67&ssl=1)

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

![Stitch client setting strings](https://i0.wp.com/www.kenwalger.com/blog/wp-content/uploads/2017/11/stitch_client_settings.png?resize=300%2C210&ssl=1)

We’ll want to grab the `<script>` information from the&nbsp;_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&nbsp;_mongodb-atlas_ from the left navigation panel and then the&nbsp;_Rules_ tab.

###### Connect the Database

Click&nbsp;_NEW_ to add a new MongoDB [collection](https://docs.mongodb.com/master/core/databases-and-collections/). For the database, I’ve called mine **glucose** and I called the collection&nbsp; **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&nbsp;_Rules_&nbsp;tab, click on the collection you just created and proceed to the&nbsp;_Filters_ tab.

![](https://i2.wp.com/www.kenwalger.com/blog/wp-content/uploads/2017/11/stitch_app_filters.png?resize=300%2C141&ssl=1)

Delete this existing filter and click&nbsp;_SAVE_. Now head on over to the&nbsp;_Field Rules_ tab. In the&nbsp;_Permissions for top-level document_ section, we’ll want to change the&nbsp;_Read_ rule to `{}` and click&nbsp;_SAVE_.

![](https://i2.wp.com/www.kenwalger.com/blog/wp-content/uploads/2017/11/stitch_app_field_rules.png?resize=300%2C297&ssl=1)

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](https://docs.mongodb.com/stitch/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.

###### HTML

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">
    <head>
        <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="https://s3.amazonaws.com/stitch-sdks/js/library/stable/stitch.min.js"></script>
    </head>
    <body>
        <h2>Sample Blood Glucose Report</h2>
        <div>
            <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>
            <hr>
            <div id="comments">
            </div>
            <hr>
            <form>
                <label for="new_comment">Add Comments:</label>
                <input id="new_comment">
                <input class="button" type="submit">
            </form>
        </div>
    </body>
</html>
```

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`&nbsp;seems like it will be necessary. Let’s tackle those functions next in `glucose.js`.

###### JavaScript

`glucose.js`

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

function displayCommentsOnLoad() {
    client.login().then(displayComments();
}

function displayComments() {
    db.collection('results').find({}).then(docs => {
        const html = docs.map(c => "<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](https://github.com/kenwalger/intro_to_stitch), with some minimal [Foundation](https://foundation.zurb.com/) 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 a&nbsp;MongoDB Atlas hosted database. Stitch has provided the backend power and we just had to write some minimal [JavaScript](https://www.javascript.com/) functions to handle the button click and document insert into our collection.

* * *

Follow me on Twitter [@kenwalger](https://www.twitter.com/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](https://www.echoskillstore.com/MongoDB-Dictionary/45103) skill for the [Amazon Echo](https://www.amazon.com/gp/product/B01DFKC2SO/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01DFKC2SO&linkCode=as2&tag=kenwalgersite-20&linkId=f9e513223de2525a72b95cf9561db55b)&nbsp;line of products. Check it out and you can say “Alexa, ask MongoDB for the definition of a&nbsp;document?” and get a helpful response.

[![Facebook](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/facebook.png?resize=48%2C48&ssl=1 "Share on Facebook")](http://www.facebook.com/sharer.php?u=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F&t=MongoDB%20Stitch%20Tutorial&s=100&p%5Burl%5D=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F&p%5Bimages%5D%5B0%5D=https%3A%2F%2Fi0.wp.com%2Fwww.kenwalger.com%2Fblog%2Fwp-content%2Fuploads%2F2017%2F06%2Fmongodbstitch-e1498689024596.png%3Ffit%3D125%252C125%26ssl%3D1&p%5Btitle%5D=MongoDB%20Stitch%20Tutorial "Share on Facebook")[![twitter](https://i0.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/twitter.png?resize=48%2C48&ssl=1 "Share on Twitter")](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F&text=Hey%20check%20this%20out "Share on Twitter")[![google_plus](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/google_plus.png?resize=48%2C48&ssl=1 "Share on Google+")](https://plus.google.com/share?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F "Share on Google+")[![reddit](https://i1.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/reddit.png?resize=48%2C48&ssl=1 "Share on Reddit")](http://www.reddit.com/submit?url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F&title=MongoDB%20Stitch%20Tutorial "Share on Reddit")[![linkedin](https://i2.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/linkedin.png?resize=48%2C48&ssl=1 "Share on Linkedin")](http://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F&title=MongoDB%20Stitch%20Tutorial "Share on Linkedin")[![mail](https://i2.wp.com/www.kenwalger.com/blog/wp-content/plugins/social-media-feather/synved-social/image/social/regular/96x96/mail.png?resize=48%2C48&ssl=1 "Share by email")](mailto:?subject=MongoDB%20Stitch%20Tutorial&body=Hey%20check%20this%20out:%20https%3A%2F%2Fwww.kenwalger.com%2Fblog%2Fnosql%2Fmongodb%2Fmongodb-stitch-tutorial%2F "Share by email")

The post [MongoDB Stitch Tutorial](https://www.kenwalger.com/blog/nosql/mongodb/mongodb-stitch-tutorial/) appeared first on [Blog of Ken W. Alger](https://www.kenwalger.com/blog).