Navigation
  • Tutorials >
  • Integrate the MongoDB Service into a Web Application using Javascript

Integrate the MongoDB Service into a Web Application using Javascript

The MongoDB Stitch Javascript SDK provides methods for integrating the MongoDB service configured in your MongoDB Stitch application into your web application.

This tutorial integrates the MongoDB Stitch Javascript SDK into an application that displays data on restaurants in a given city. The application uses the MongoDB Stitch SDK to perform anonymous user authentication and access a MongoDB database via the MongoDB service.

You can apply the general strategies and structure used in this tutorial as a baseline for utilizing the MongoDB Stitch Javascript SDK and MongoDB service in your own application.

Considerations

This tutorial does not cover the entirety of the MongoDB Stitch Javascript SDK. For complete documentation on the MongoDB Stitch Javascript SDK, see the JavaScript API.

Javascript Development

A full description of Javascript, HTML, or web programming in general is beyond the scope of this tutorial. This tutorial assumes prior knowledge and experience of Javascript development and its related subject matter.

Authentication

This tutorial provides instructions on using MongoDB Stitch anonymous user authentication for interfacing with the MongoDB service. While MongoDB Stitch supports Facebook and Google user authentication, those integrations are out of scope for this tutorial. For complete documentation on configuring authentication in MongoDB Stitch, see Authentication.

Procedure

A. Create a MongoDB Stitch App

Estimated Time to Complete: ~12 minutes

1

Log into Atlas.

To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.

2

Create an Atlas cluster.

If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.

Important

You must deploy the Atlas cluster with MongoDB version 3.4 or greater.

Atlas provides a Free Tier M0 replica set as well as paid M10+ clusters. Free Tier deployments have restrictions as compared to paid M10+ deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier) Limitations.

3

Create and populate a restaurants collection in a guidebook database.

Use Compass or the mongo shell to connect to your new Atlas cluster and create and populate a new database. The application expects documents in the guidebook.restaurants collection to have the following schema:

{
   "name" : <string>,
   "cuisine" : <string>,
   "location" : <string>,
   "comments" : [
      { "user_id" : <string>, "comment" : <string> },
      ...
   ]
}
4

Add a MongoDB Stitch application.

  1. In Atlas, click Stitch Apps in the left-hand navigation.
  2. Click the Create New Application. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  3. Select your Atlas cluster for your MongoDB service.
  4. Click Create.

Upon creation of your app, you will be redirected to the MongoDB Stitch console. Your app is created with a MongoDB service named mongodb-atlas.

B. Create a Namespace and Rules in Your MongoDB Stitch App

Estimated Time to Complete: ~3 minutes

1

Create a namespace for the restaurants collection in the guidebook database.

  1. Click on the MongoDB service mongodb-atlas.
  2. Click the Rules tab.
  3. Click New.
  4. Enter guidebook in the Database text box.
  5. Enter restaurants in the Collection: text box.
  6. Click Create.

Note

You must add rules for each collection the MongoDB service accesses.

2

Review the read rule for the top-level document in guidebook.restaurants.

Modify the read rule for the top level document to the following and click Save:

{ }

The new rule specifies that all the fields in the documents are always readable.

For more information on MongoDB read rules, see MongoDB Service Read Rule.

3

Review the write rule for the top-level document in guidebook.restaurants.

Modify the write rule for the top level document to the following and click Save:

{ }

The new rule specifies that all fields are writable. For more information on MongoDB write rules, see MongoDB Service Write Rule.

4

Delete the owner_id field.

Hover over the field and click the x on the right-hand side.

5

Review All Other Fields and click Save.

By default, the All Other Fields flag is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable All Other Fields to control the shape of the documents.

C. Enable Anonymous Authentication

Estimated Time to Complete: ~1 minute

  1. Log in to Atlas and go to Stitch Apps.
  2. Select your MongoDB Stitch application. You will be redirected to the MongoDB Stitch console to the Getting Started page. If you are not on the Getting Started page, click Getting Started in the left-hand navigation bar.
  3. Click Turn On Authentication.
  4. Toggle the Anonymous Authentication switch.

For complete documentation on configuring authentication in MongoDB Stitch, see Authentication.

D. Update the MongoRestaurant Sample Application Code

Estimated Time to Complete: ~5 minutes

1

Download the MongoRestaurant application source.

Download the MongoRestaurant application from the Stitch github example repository.

Clone or fork the github repository and navigate to MongoRestaurant/MongoRestaurant-javascript.

2

In app.js, replace STITCH-APP-ID with your MongoDB Stitch application ID.

const stitchClient = new stitch.StitchClient("STITCH-APP-ID");
const mongoClient = stitchClient.service("mongodb", "mongodb-atlas");

To locate your application ID:

  1. Log in to Atlas and go to Stitch Apps.
  2. Select your MongoDB Stitch application. You will be redirected to the MongoDB Stitch console to the Getting Started page. If you are not on the Getting Started page, click Getting Started in the left-hand navigation bar.
  3. Click Clients in the navigation bar.
  4. Retrieve the value for App Id.
3
4

In app.js, review the creation of an instance of the StitchClient class and the call to its .service() method.

The MongoDB Stitch SDK provides the following objects and related methods for interfacing with the MongoDB Stitch SDK and the MongoDB Stitch MongoDB service:

  • StitchClient(String clientAppID)

    This object handles interactions between the application and the MongoDB Stitch service, including authentication or MongoDB Stitch pipelines. Takes a string representing the MongoDB Stitch application ID as parameters.

  • StitchClient.service(String service, String serviceName)

    Returns a factory object that handles interactions between the application and the specified MongoDB Stitch service. For the MongoDB service, set service to mongodb and serviceName to mongodb-atlas.

    • To access a database, use the db(String databaseName) method on the factory object. This method returns a database object.
    • To access a collections, use the collection(String collectionName) method on the database object. This method returns a collection object.

Create and instantiate the StitchClient object. You can then create additional variables to store the MongoDB service object, the MongoDB database object, and the MongoDB collection object.

const stitchClient = new stitch.StitchClient("STITCH-APP-ID");
const mongoClient = stitchClient.service("mongodb", "mongodb-atlas");

const db = mongoClient.db("guidebook");
const coll = db.collection("restaurants");
5

In app.js, review the use of anonymous user authentication.

To perform anonymous authentication, call the login method on the StitchClient object without providing a username and password.

  • StitchClient.login()

    Authenticates the client anonymously through MongoDB Stitch.

function doAnonymousAuth() {
    stitchClient.login().then( result => {
        console.log("authenticated");
        
    }).catch( err => {
        console.error("Error performing auth",err)
    });
}
6

In app.js, review how to write data to the MongoDB server from Stitch.

You can perform operations on either the database object or the collection object, depending on your objectives. For example, to update a document in a collection, use the updateOne() method on the collection object.

coll.updateOne(query,update).then( () => {
   refreshComments();
}).catch( err => {
    console.error("Error while adding comment", err)
});
7

In app.js, review how to read data from the MongoDB server from Stitch.

You can perform operations on either the database object or the collection object, depending on your objectives. For example, to find a document in a collection, use the find() method on the collection object.

coll.find({"name" : text }).then( payload => {
    console.log(payload);
8

Open index.html in a browser.

Application Code

index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!doctype html>
<html>
    <head>
        <title>MongoRestaurant</title>
        <meta charset="utf-8">
    </head>
    <body>
        <script src="https://s3.amazonaws.com/stitch-sdks/js/library/stable/stitch.min.js"></script>
        <script defer type="text/javascript" src="app.js"></script>
        <div> 
            <input id="restaurantName" type="text" > </input>
            <button id="button-search">Search</button>
        </div>
        <div>
            <p id="resultFound"></p>
            <p id="location"></p>
            <p id="cuisine"></p>
        </div>
        <div>
            <button id="button-write">Write Comment</button>
            <button id="button-refresh">Refresh Comments</button>
        </div>
        <div id="commentFeed">
        </div>
    </body>
</html>

app.js

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
document.addEventListener('DOMContentLoaded',() => {
    
    'use strict'
    
    // Replace the STITCH-APP-ID with your Stitch Application ID
    const stitchClient = new stitch.StitchClient("STITCH-APP-ID");
    const mongoClient = stitchClient.service("mongodb", "mongodb-atlas");
    
    const db = mongoClient.db("guidebook");
    const coll = db.collection("restaurants");
    
    const writeButton = document.getElementById('button-write');
    const searchButton = document.getElementById('button-search');
    const refreshButton = document.getElementById('button-refresh');
    
    var restaurantName = ""
    
    function doAnonymousAuth() {
        stitchClient.login().then( result => {
            console.log("authenticated");
            
        }).catch( err => {
            console.error("Error performing auth",err)
        });
    }
    
    function searchRestaurant(text) {
        clearComments()
        
        coll.find({"name" : text }).then( payload => {
            console.log(payload);
            
            if (payload.length == 0){
                document.getElementById("resultFound").innerHTML = "Result not found";
            } else {
                console.log("result returned");
                document.getElementById("resultFound").innerText = "Found Restaurant";
                document.getElementById("cuisine").innerText = payload[0].cuisine;
                document.getElementById("location").innerText = payload[0].location;
                restaurantName = document.getElementById("restaurantName").value;
                
                const comments = payload[0].comments;
                for (var i = 0; i < comments.length; i++){
                    writeComment(comments[i].comment, comments[i].user_id);
                }
            }
        }).catch ( err => {
            console.error("error in search", err);
        });
    }
    
    function writeComment(comment, user_id) {
        var commentFeed = document.getElementById('commentFeed');
        
        var newDiv = document.createElement('div');
        var userName = document.createElement('p');
        var userComment = document.createElement('p');
        
        if (user_id === null){
            const query = {"name" : restaurantName};
            const update = {
                "$push" : {
                    "comments" : {
                        "comment" : comment, 
                        "user_id" : stitchClient.authedId()
                    }
                }
            }
            
            coll.updateOne(query,update).then( () => {
               refreshComments();
            }).catch( err => {
                console.error("Error while adding comment", err)
            });
        } else {
            userComment.appendChild(document.createTextNode(comment))
            userName.appendChild(document.createTextNode("-" + user_id));
        
            newDiv.appendChild(userComment);
            newDiv.appendChild(userName);
            commentFeed.appendChild(newDiv);
        }
    }
    
    function refreshComments() {
        clearComments()
        
        coll.find({"name" : restaurantName}).then( payload => {
            const comments = payload[0].comments;
            for (var i = 0; i < comments.length; i++){
                writeComment(comments[i].comment, comments[i].user_id);
            }
        }).catch( err => { 
            console.error("error while submitting", err)
        });
    }
    
    function clearComments() {
        document.getElementById('commentFeed').innerText = "";
    }
    
    writeButton.onclick = () => {
        if (restaurantName != ""){
            
            var inputVal = prompt("Enter your comment : ", "comment");
            writeComment(inputVal, null);
        } else {
            alert("You must search for a valid restaurant to write a comment.")
        }
    }
    
    searchButton.onclick = () => {
        var text = document.getElementById("restaurantName").value;
        searchRestaurant(text);
    }
    
    refreshButton.onclick = () => {
        refreshComments();
    }
    
    doAnonymousAuth()
    
});