Stitch

MongoDB provides a serverless platform to build an application quickly without setting up server infrastructure. MongoDB Stitch is designed as an upgraded version of MongoDB Atlas. It automatically integrates the connection to our database. Stitch illuminates the development and implementation process. It achieved it by neglecting the requirement of building and deploying our backend. MongoDB stitch is available as a backend service that allows us to configure data-authentication, data access rules, and services easily.

MongoDB Stitch

MongoDB stitch provides an upgradable infrastructure design to handle the request. It also coordinates the services and database interactions. i.e., we don't need to spend time and resources on tasks such as configuring our servers, etc.

For example- we can use MongoDB Stitch to generate a pipeline that would allow us to accept payment using Stripe via the HTTP service, update the date of purchase, and send a confirmation email with the Mailgun service.

Creating a Stitch App using Stitch UI

Step 1: Go to https://www.mongodb.com/cloud/atlas page, and log on to your Atlas account.

MongoDB Stitch

Step 2: Now, you have to create a cluster to use with your MongoDB Stitch app, follow these steps:

  • Click on the Clusters button on the left navigation window, then click on the Build New Cluster button.
    MongoDB Stitch
  • Select your preferred service provider, region, tier, and other required settings.
    MongoDB Stitch
  • The name of the cluster is Cluster0 by default. If you want to change the name of the cluster, you have to do it at this step because the cluster name cannot be changed once configured.
    MongoDB Stitch
  • Finally, click the Create Cluster button to save the changes you made.

Step 3: Inside the MongoDB Atlas, click Stitch Apps from the left-hand navigation window.

MongoDB Stitch

Step 4: After that, click on the Create New Application button.

MongoDB Stitch

Step 5: On the Create a new application pop-up window, enter a Name for your Stitch app.

MongoDB Stitch

Step 6: Choose a cluster in your project from the Link to Cluster dropdown dialogue. MongoDB Stitch automatically creates a MongoDB service that Is linked to your cluster.

Step 7: Fill in the name for the service that Stitch will create in the Stitch Service Name field.

MongoDB Stitch

Step 8: Choose a deployment model and deployment region for your application. Then click on the Create button.

MongoDB Stitch

The following window will appear after the successful deployment.

MongoDB Stitch

Creating a Stitch App using Stitch CLI

Step 1: Firstly, create a new directory for your application and add a stitch.json file to the root level of the directory. The file must contain an empty JSON object.

Step 2: Authenticate the MongoDB Stitch application with Atlas using an API key.

snippet
stitch-cli login --api-key=my-api-key --private-api-key=my-private-api-key

Step 3: Now, import the Stitch CLI library using the "stitch-cli import" command.

Step 4: You should verify if your application is created or not.

Query Anywhere with Stitch

Using the MongoDB query language, we can query our stored data in MongoDB directly from our client application code. The Stitch server for the MongoDB collection allows us to securely filter the result using the specified data access rules based on the logged-in user or the contents of each document.

The Student collection contains documents describing each student in an example collage. Each document includes the student's name, email, address, fees, and information on the student's stream. In the example given below, we compare the student's collection for all the documents and return the formatted results as a table.

HTML File:

snippet
<!-- Base Stitch Browser SDK --> <script src="https://s3.amazonaws.com/stitch                      sdks/js/bundles/4.0.13/stitch.js"></script>

<div class="results-bar">
  <p>Count of Results:</p>
  <span id="num-results" class="results-bar__count"></span>
</div>
<table class="table table-striped">
  <thead class="thead">
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Class</th>
      <th>Batch</th>
      <th>Fees</th>
    </tr>
  </thead>
  <tbody id='students'></tbody>
</table>

Java Script File:

snippet
const {
  Stitch,
  RemoteMongoClient,
  UserPasswordCredential
} = stitch;

const stitchClient = Stitch.initializeDefaultAppClient("stitch-quickstarts-zhpox");

login("rookienerd@example.com", "password123").then(() => {
  // Initialize a MongoDB Service Client
  const mongodb = stitchClient.getServiceClient( RemoteMongoClient.factory,
    "mongodb-atlas");
  // Get a hook to the student collection
  const students = mongodb.db("Admin").collection("students");
  
  return students.find({}, {
    // limit: 2,
    // sort: { "fees": -1 }
  })
    .asArray();
})
  .then(displayStudents)

function login(email, password) {
  const credential = new UserPasswordCredential(email, password);
  return stitchClient.auth.loginWithCredential(credential);
}


// Renders the the students' information in the table
function displayStudents(students) {
  const employeesTableBody = document.getElementById("students");
  const numResultsEl = document.getElementById("num-results");
  const tableRows = students.map(student => {
    return '
      <tr>
        <td>${student.name.last}, ${student.name.first}</td>
        <td>${student.email}</td>
        <td>${student.role}</td>
        <td>${student.manager.name.first}${student.manager.name.last} (${student.admin.id || "no manager"})</td>
        <td>${student.fees}</td>
      </tr>
    ';
  });
  studentTableBody.innerHTML = tableRows.join("");
  numResultsEl.innerHTML = student.length;
}

Protecting Data with Rules

We can use collection rules if we don't want to allow every student to see the data of every other student. We can use it to control the data that all the user can access it without altering the pattern of the query.

Creating a Blog App

Here we are creating a blog and commenting system using Stitch. We are using MongoDB Stitch JavaScript SDK and the MongoDB service to add and query comments directly from the client code.

The architecture of the Blog App

The blog app architecture requires the following features:

  • Log in ability.
  • Blog post storage ability.
  • Blog posts comment ability.

When we use MongoDB Atlas Cluster, we can store comments and the authentication details that allow users to post comments using a temporary account.

The three main components of blog architecture are:

  • A web front-end,
  • Stitch application,
  • MongoDB Atlas database.

The front-end of the blog application architecture handles the display and user interaction. Stitch manages all the request from the front-end and allow only verified requests to the database, which saves comments for our users.

Creating Backend for the Blog App

The backend of the blog app is used to store comments and other details like - authenticate and authorize users, finding existing comments for a blog post etc. We are storing the comments within a sample of MongoDB application. Here, we are going to limit the permission for the user to create, edit, and delete comments only associated with their user ID by authorization. We also need to make sure that a user can't log in as another user; we can achieve this by using the built-in user management system in the MongoDB stitch.

Requirements:

  • MongoDB Atlas account.
  • And a MongoDB cluster that is hosted on Atlas. We suggest you to create an M0 Atlas cluster that is free of cost and good for learning purpose.

Step 1: Create a Stitch Application as directed above.

Step 2: Turn on the Anonymous Authentication inside the Stitch application that you have created.

Step 3: Finally, configure the blog.comments MongoDB Collection

  • Click on rules under MongoDB Atlas from the left-hand navigation of the Stitch UI.
  • Then, click on Add Collection.
  • Now, enter the blog for the Database Name, and enter comments for the Collection name.
  • Select the "No Template" option and click on Add Collection.

Step 4: Enable reading and writing to the comments.

Step 5: Finally, post your application by clicking on Review & Deploy Changes in the pop-up at the top of the Stitch GUI.

Creating a Web Client for the blog app

Step 1: Create an HTML page as follows.

snippet
<html>
  <head>
  </head>
  <body>
    <h3>This is the first blog post of rookienerd</h3>
    <div id="content">
      Learn technology from rookienerd to keep yourself industry ready.
    </div>
    <hr>
    <div id="comments"></div>
  </body>
</html>

Step 2: Now, attach the following JavaScript SDK. To attach the MongoDB Stitch SDK. Add the script tag given below to the head section of your html file.

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

Step 3: Initialize the app client and a MongoDB Service client to store comments in MongoDB. Replace the app id with your Stitch <app-id>. You find your App ID on the client page of Stitch Interface.

snippet
<script>
  // it initializing the App Client
  const client = stitch.Stitch.initializeDefaultAppClient("<give-your-app-id-here>");
  // Now, it will get a MongoDB Service Client
  const mongodb = client.getServiceClient(
    stitch.RemoteMongoClient.factory,
    "mongodb-atlas"
  );
  // Getting a reference to the blog database
  const db = mongodb.db("blog");
</script>

Step 4: Now, add the script given below to query and display the comments when page loads.

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

Step 5: You have to create a file that allows the user to login and display the comment during the loading time.

snippet
function displayCommentsOnLoad() {
  client.auth

    .loginWithCredential(new stitch.AnonymousCredential())

    .then(displayComments)
    .catch(console.error);
}

Step 6: Now, create a form to submit the comments.

snippet
function addComment() {
  const newComment = document.getElementById("new_comment");
  console.log("add comment", client.auth.user.id)
  db.collection("firstcomment")
    .insertOne({ owner_id : client.auth.user.id, comment: newComment.value })
    .then(displayComments);
  newComment.value = "";
}
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +