Navigation

Building A Blog 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, create a script tag, and add the following code, which initializes the Stitch client and MongoDB client:

<script>

  const client = stitch.Stitch.initializeDefaultAppClient('<your-app-id>');

  const db = client.getServiceClient(stitch.RemoteMongoClient.factory,
    "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. Pass a new stitch.AnonymousCredential instance to the loginWithCredential function to authenticate, and then implement the logic to display blog comments. In the blog.html file, update the <script> block to include the following code to display comments.

function displayCommentsOnLoad() {
  client.auth
    .loginWithCredential(new stitch.AnonymousCredential())
    .then(displayComments)
    .catch(console.error);
}

function displayComments() {
  db.collection('comments').find({}, {limit: 1000}).asArray()
    .then(docs => {
      const html = docs.map(c => "<div>" + c.comment + "</div>").join("");
      document.getElementById("comments").innerHTML = html;
    });
}

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

<body onload="displayCommentsOnLoad()">
9

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() {
  const commentEl = document.getElementById('new_comment');
  const comment = {
    owner_id : client.auth.user.id,
    comment: commentEl.value
  }
  db.collection('comments').insertOne(comment)
    .then(displayComments);
  commentEl.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 Providers for more information.

Complete blog.html

For reference, here is the entire app in one code block:

<html>
   <head>
      <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.0.0/stitch.js"></script>
      <script>
         const client = stitch.Stitch.initializeDefaultAppClient('<your-app-id>');
         const db = client.getServiceClient(stitch.RemoteMongoClient.factory,
            "mongodb-atlas").db('blog');

         function displayCommentsOnLoad() {
            client.auth.loginWithCredential(new stitch.AnonymousCredential())
               .then(() => {
                  displayComments();
               }).catch(err => {
                  console.error(err)
               });
         }

         function displayComments() {
               db.collection('comments').find({}, {limit: 1000}).asArray().then(docs => {
               const html = docs.map(c => "<div>" + c.comment + "</div>").join("");
               document.getElementById("comments").innerHTML = html;
            });
         }

         function addComment() {
            const newComment = document.getElementById("new_comment");
            console.log('add comment', client.auth.user.id)
            db.collection("comments").insertOne({owner_id : client.auth.user.id,
               comment: newComment.value}).then(displayComments);
            newComment.value = "";
         }
      </script>
   </head>
   <body onLoad="displayCommentsOnLoad()">
      <h3>This is a great blog post</h3>
      <div id="content">
         I like to write about technology because I want to get on the
         front page of hacker news.
      </div>
      <hr>
      <div id="comments"></div>
      <hr>
      Add a Comment: <input id="new_comment"><input type="submit" onClick="addComment()">
   </body>
</html>