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.
  2. Wait for your application to initialize.
4

Turn on anonymous authentication

In the MongoDB Stitch application page, turn on Anonymous Authentication.

5

Add the MongoDB Stitch JavaScript SDK to our HTML page

  1. In the left navigation panel under STITCH CONSOLE, click Clients.
  2. Under Importing on a Web Page click COPY LINE.
  3. Paste the line you just copied into the head section near the top of our blog.html file.
6

Initiate a client connection

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

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

Replace blog_comments-abcde in the above with your App Id. You will find the App Id at the top of the Clients page for your MongoDB Stitch app.

7

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({}).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.

8

Set up our comments collection

  1. In the left navigation panel, under Atlas Clusters click mongodb-atlas and select the Rules tab.
  2. Click New to add a new MongoDB Collection.
  3. Enter blog for the Database, comments for the Collection, and click Create.
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. Under Atlas Clusters click mongodb-atlas
  2. Click the Rules tab
  3. Under MongoDB Collections click blog.comments
  4. Click the Filters tab.
  5. Delete the existing filter and click SAVE.
  6. Click the Field Rules tab.
  7. 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 Service 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').insert({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/stable/stitch.min.js"></script>
    <script>
      const client = new stitch.StitchClient('blog_comments-abcde');
      const db = client.service('mongodb', 'mongodb-atlas').db('blog');

      function displayComments() {
        db.collection('comments').find({}).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').insert({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).