Navigation

Build Your First MongoDB Stitch App

Overview

Estimated Time to Complete: ~15 minutes

To get started with Stitch, we’ll work with a single HTML file that contains a blog post. Using Stitch, we’ll add commenting functionality.

1

Create the HTML page

Create a file called blog.html that contains the following.

<html>
  <head>
  </head>
  <body>
    <h3>Aspirational blog post</h3>
    <div id="content">
      I like to write about technology, because I want to get
      on the front page of hacker news (in a good way).
    </div>
    <hr>
    <div id="comments"></div>
  </body>
</html>
2

Create an Atlas cluster

To use MongoDB Stitch, you must be logged in to MongoDB Atlas.

  1. Go to Atlas and login or create an account. No credit card is required.
  2. When prompted, create a group. This will be used to identify your Atlas clusters.
  3. Next, deploy an M0 (FREE) Atlas cluster.
  4. Wait for your cluster to initialize.
3

Initialize MongoDB Stitch app

  1. Click Stitch Apps in your MongoDB Atlas console and then click Create New Application. Name your application blog_comments and click Create.
  2. Wait for your application to initialize. Upon creation of your app, you will be redirected to the MongoDB Stitch console.
4

Turn on anonymous authentication

In the MongoDB Stitch Getting Started page, turn on Anonymous Authentication.

5

Set up our comments collection

  1. In the MongoDB Stitch Getting Started page, add a new MongoDB Collection in the Initialize a MongoDB Collection section.
  2. Enter blog for the Database Name, comments for the Collection Name, and click Add Collection.
6

Add the MongoDB Stitch JavaScript SDK to our HTML page

  1. In the MongoDB Stitch Getting Started page, click on Execute a Test Request section.
  2. In the Importing on a Web Page section, click COPY.
  3. Paste the line you just copied into the head section near the top of our blog.html file and save.
7

Initiate a client connection

In our blog.html file, just below the first script tag, add the following.

<script>
  const client = new stitch.StitchClient('<your-app-id>');
  const db = client.service('mongodb', 'mongodb-atlas').db('blog');
</script>

Replace <your-app-id> in the above with your App ID. You can find the App ID in the MongoDB Stitch Getting Started page, Execute a Test Request section.

8

Display comments

MongoDB Stitch requires clients to authenticate before interacting with any MongoDB Stitch service. Use StitchClient.login() to anonymously authenticate and then display comments. In the blog.html file, update the script block to include support for displaying comments.

function displayComments() {
  db.collection('comments').find({}).execute().then(docs => {
    var html = docs.map(c => '<div>' + c.comment + '</div>').join('');
    document.getElementById('comments').innerHTML = html;
  });
}

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

Update the body tag in blog.html to display comments when the page loads.

<body onload="displayCommentsOnLoad()">

Open the developer console and reload the blog.html page. You will see an error because we have not yet set up our comments collection.

9

Allow anyone to read comments

By default, MongoDB Stitch configures authorization such that data may only be read and written by the owner. Because we are not creating private data, we can relax the default authorization for blog comments.

  1. In Stitch, click on mongodb-atlas on the left-hand navigation.
  2. Under MongoDB Collections, click blog.comments.
  3. Click the Filters tab.
  4. Delete the existing filter and click SAVE.
  5. Click the Field Rules tab.
  6. For Permissions on top-level document, change the READ rule to {} and click SAVE.

We have now configured authorization on blog comments so that anyone can read anything in the blog.comments collection, but only the owners can edit or delete their own comments.

See MongoDB Rules for more information on configuring rules for Atlas clusters.

10

Add a form for creating comments

Now we can add comments. At the bottom of the blog.html file add the following to create a form for adding comments.

<hr>
Add comment:
<input id="new_comment"><input type="submit" onClick="addComment()">

Add the addComment() function to your script block.

function addComment() {
  var c = document.getElementById('new_comment');
  db.collection('comments').insertOne({owner_id : client.authedId(),
                                       comment: c.value})
    .then(displayComments);
    c.value = '';
 }

You should now be able to add comments to your blog post.

We are using anonymous login here, but you can configure your app to use email/password authentication, use Google or Facebook via OAuth, or set up custom authentication based on JSON Web Tokens. See Authentication for more information.

Completed blog.html

For reference, here is the entire app in one block.

<html>
  <head>
    <script src="https://s3.amazonaws.com/stitch-sdks/js/library/v2/stable/stitch.min.js"></script>
    <script>
      const client = new stitch.StitchClient('<your-app-id>');
      const db = client.service('mongodb', 'mongodb-atlas').db('blog');

      function displayComments() {
        db.collection('comments').find({}).execute().then(docs => {
          var html = docs.map(c => '<div>' + c.comment + '</div>').join('');
          document.getElementById('comments').innerHTML = html;
        });
      }

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

      function addComment() {
        var c = document.getElementById('new_comment');
        db.collection('comments').insertOne({owner_id : client.authedId(),
                                          comment: c.value})
          .then(displayComments);
        c.value = '';
      }
    </script>
  </head>
  <body onload="displayCommentsOnLoad()">
    <h3>Aspirational blog post</h3>
    <div id="content">
      I like to write about technology, because I want to get
      on the front page of hacker news (in a good way).
    </div>
    <hr>
    <div id="comments"></div>
    <hr>
    Add comment:
    <input id="new_comment"><input type="submit" onClick="addComment()">
  </body>
</html>

Next Steps

Create a ToDo app using MongoDB Stitch, see ToDo (Web App).