Navigation

Basic Blog

Overview

Estimated Time to Complete: ~15 minutes

What We’ll Build

In this tutorial, we’ll create a blog commenting system backed by Stitch. We’ll use Stitch to add and query for comments directly from the client code using the Stitch JavaScript SDK and the MongoDB Service.

Prerequisites

Before we begin, you’ll need the following:

  • A MongoDB Atlas acount.

  • A MongoDB cluster hosted on Atlas.

    Create a Free Atlas Cluster

    You can create an M0 Atlas cluster for free. No credit card is required to get started.

    To get up and running with a free M0 cluster, follow the MongoDB Atlas Getting Started guide.

Procedure

A. Create the Blog Post Layout

Let’s begin by creating a basic blog post with no commenting functionality. Create a file called blog.html and copy the following HTML into the file:

blog.html
<html>
  <head>
  </head>
  <body>
    <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>
  </body>
</html>

B. Create and Configure a MongoDB Stitch Application

1

Create a Stitch Application

We need to set up a Stitch application to connect the blog to MongoDB.

To create a new Stitch application:

  1. Log in to MongoDB Atlas.
  2. Click Stitch Apps in the left-hand navigation of the MongoDB Atlas console.
  3. Click Create New Application.
  4. Give the application a name (e.g. BlogTutorial) and click Create.
  5. Wait for your application to initialize. Upon creation of your app, you will be redirected to the Stitch UI.
2

Turn on Anonymous Authentication

We need to enable an authentication provider so that users can log in and query MongoDB.

From the Getting Started page of the Stitch UI, enable Anonymous Authentication under the Turn On Authentication heading.

Note

This tutorial uses anonymous authentication, but you can configure your app to let users authenticate with another method, such as email/password, Google OAuth, or a custom authentication system based on JSON Web Tokens.

See the Authentication Providers Overview for more information, including a complete list of available authentication providers.

3

Configure the blog.comments MongoDB Collection

We need to configure rules for the comments collection before Stitch will allow users to query it.

To configure the collection:

  1. Click Rules under MongoDB Atlas in the left-hand navigation of the Stitch UI.
  2. Click Add Collection.
  3. Enter blog for the Database Name.
  4. Enter comments for the Collection Name.
  5. Select No Template
  6. Click Add Collection.

You should now see the Permissions tab of the rules for the comments collection. The default role doesn’t allow any user to read or write to the collection.

To enable reading and writing to the comments collection:

  1. Click the Read and Write checkboxes for the default role.
  2. Click Save.

C. Add a Commenting System to the Blog Post

1

Include the MongoDB Stitch JavaScript SDK

We need the JavaScript SDK to communicate with Stitch from our blog code.

To include the SDK, add the following <script> tag to the <head> section of blog.html:

<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.0.0/stitch.js"></script>
2

Initialize Stitch Clients

Apps communicate with Stitch by calling methods on client objects from the Stitch SDK. We need to initialize an app client and a MongoDB Service client to store comments in MongoDB.

To set up Stitch:

  1. Paste the following <script> tag in blog.html beneath the tag that imports the Stitch SDK:

    <script>
      // Initialize the App Client
      const client = stitch.Stitch.initializeDefaultAppClient("<your-app-id>");
      // Get a MongoDB Service Client
      const mongodb = client.getServiceClient(
        stitch.RemoteMongoClient.factory,
        "mongodb-atlas"
      );
      // Get a reference to the blog database
      const db = mongodb.db("blog");
    </script>
    
  2. In the code you just pasted, replace <your-app-id> with your Stitch application’s App ID. You can find the App ID on the Clients page of the Stitch UI.

3

Query and Display Comments on Page Load

We can use the MongoDB Service client we just created to query the blog.comments collection. Once we have the comments documents, we can map them to HTML and display them on the blog post.

To query and display comments, add the following function to the <script> tag:

function displayComments() {
  db.collection("comments")
    .find({}, {limit: 1000})
    .asArray()
    .then(docs => docs.map(doc => `<div>${doc.comment}</div>`))
    .then(comments => document.getElementById("comments").innerHTML = comments)
}

Important

MongoDB Stitch requires users to log in before interacting with any Stitch service. Even though we configured the rules for the blog.comments collection, this query won’t work unless a user is logged in.

4

Log In and Display Comments On Load

Users log in to Stitch applications with a provider-specific credential object that we pass to the loginWithCredential() function. We created an anonymous authentication provider in Stitch, so we need users to log in with an anonymous credential.

To set up anonymous authentication in blog.html:

  1. Add the following function to the <script> tag:

    function displayCommentsOnLoad() {
      client.auth
        .loginWithCredential(new stitch.AnonymousCredential())
        .then(displayComments)
        .catch(console.error);
    }
    
  2. Update the <body> tag in blog.html to display comments when the page loads.

    <body onload="displayCommentsOnLoad()">
    
5

Add a Form for Submitting Comments

We now have everything we need to query and display comments that are already in MongoDB. All that’s left to do is to wire up a form that lets users insert new comments.

To let users add new comments:

  1. Add the addComment() function to the <script> tag:

    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 = "";
    }
    
  2. Add a comment form by pasting the following code at the bottom of the <body> tag in blog.html:

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

Summary

Nice work! At this point, you should be able to refresh the page and submit a comment on the blog post.

You can see the final, completed HTML file for this tutorial here.

What’s Next?