Navigation

ToDo (Web App)

This tutorial demonstrates how to use MongoDB Stitch to integrate the following services for an application:

  • Google/Facebook user authentication services and
  • MongoDB service.

To demonstrate, the tutorial incorporates the services into a provided ToDo application. The ToDo application is a web application that maintains a personal todo list. Users can log in using Google or Facebook credentials, add items to the list, check completed items and delete completed items.

Prerequisites

For this app, you need the following:

  • A MongoDB Atlas cluster using MongoDB version 3.4+. The tutorial uses an Atlas Free Tier cluster.
  • A developer account with either Google or Facebook (or both) for user authentication services.
  • Node version 6.0.0+ or above installed on the machine you will run the ToDo app. See https://nodejs.org/en/download/ for installation instructions.

The ToDo app writes to the items collection in the todo database. Ensure this collection is empty before starting this procedure. To empty a collection, use the db.collection.drop() method.

Stitch Access to the MongoDB Service

By default, each MongoDB Stitch app automatically creates a user with the necessary permissions to read and write to the todo.items collection on the linked Atlas MongoDB deployment. Do not modify this user’s permissions, or you may prevent the application from running correctly.

Additionally, MongoDB Stitch cannot override any document validation rules configured on the linked Atlas MongoDB deployment. Do not create any document validation rules for the todo.items database, or you may prevent the application from running correctly.

Procedure

A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 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

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. Configure the MongoDB service

Estimated Time to Complete: ~5 minutes

You must specify a namespace for each collection the MongoDB Stitch MongoDB service accessess. A namespace is a combination of the database name and the name of the collection. In MongoDB Stitch, each namespace contains rules and filters that control access to documents during read and write operations. MongoDB Stitch creates basic rules and filters by default when you add a namespace in MongoDB Stitch. See MongoDB Service Rules for more information.

1

Configure the MongoDB service.

Create a namespace for the todo.items collection:

  1. Click on the MongoDB service mongodb-atlas.
  2. Click on the Rules tab.
  3. In the Rules tab, click New to add a new namespace. Enter the following information:
    • For Database, enter todo.
    • For Collection, enter items.
  4. Click Create.
2

Review Read Rules for Top-Level Documents in todo.items.

To view the read rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following read rule for the top-level document:

{
  "owner_id": "%%user.id"
}

With this rule, read and write operations can access all fields in a document if the document contains an owner_id field whose value equals the user ID (%%user.id) of the client issuing the read. If the owner_id field in the document does not equal the client user id, no field in the document is readable.

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

3

Review Write Rules for Top-Level Documents in todo.items.

To view the write rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following write rule for the top-level document:

{
  "owner_id": "%%user.id"
}

With this rule, the write operation must result in a document where the owner_id equals the user ID of the client issuing the write. If the value of owner_id does not match the client user ID, MongoDB Stitch blocks the write.

Modify the write rule to the following and click Save:

{
  "%or": [
    { "%%prevRoot.owner_id": "%%user.id" },
    { "%%prevRoot": { "%exists": 0 } }
  ]
}

The new rule specifies that the fields in a document are writable if either:

  • The write operation modifies a document where the value of owner_id previous to the write operation (%%prevRoot.owner_id) equaled the user ID (%%user.id) of the client issuing the write. An example of this kind of write operation is a client modifying a document that it previously inserted.
  • The write operation modifies a document where there was no document (%exists) previous to the write operation (%%prevRoot). An example of this kind of write operation is an insert of a new document.

For more information on MongoDB write rules, see MongoDB Service Write Rule.

4

Review Validation Rules for owner_id field in todo.items.

Click on the owner_id field to view its rules.

To view a validation rule, click on the owner_id in the Field Rules view.

By default, the collection has the following validation rule specified on the owner_id field that determines whether a write operation is permissible:

{
  "%or": [
    { "%%prev": "%%user.id" },
    { "%%prev": { "%exists": false } }
  ]
}

With this rule, a write operation is valid if either:

  • The write operation modifies a document where the value of owner_id previous to the write operation (%%prev) equals the user ID (%%user.id) of the client issuing the write. An example of this kind of write operation is a client modifying a document that it previously inserted, or
  • The write operation modifies a document where there was no value for the owner_id field (%exists) previous to the write operation (%%prev). An example of this kind of write operation is an insert of a new document.

Modify the validation rule to the following and click Save:

"%%user.id"

The new rule requires that the value of owner_id equals the user ID (%%user.id) of the client issuing write. That is, MongoDB Stitch fails write operations that violate this rule.

For more information on validation rules, see MongoDB Service Validation.

5

Review All Other Fields Enabled option for todo.items.

By default, Allow 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 Allow All Other Fields to control the shape of the documents. For examples, see Integrate ToDo with Twilio.

6

Review Filters for todo.items.

Click on the Filters.

By default, the collection has the following filter rule:

When Match Expression
{ "%%true": true } { "owner_id": "%%user.id" }

This filter indicates that when %%true equals true (i.e. always), apply the following filter { "owner_id": "%%user.id" } to the read and write operations. This filter is in addition to the query predicates for read and write operations.

For more information on filters, see MongoDB Service Filters.

C. Set Up Facebook Auth

Estimated Time to Complete: 10 minutes

1

Set up an app in Facebook.

  1. Log in to your Facebook Developer account. If you do not have a Facebook developer account or even a Facebook account, see Facebook - Register and Configure an App.

  2. Add a new Facebook application.

  3. Once created, your application view opens to Product Setup. If not, go to your newly added app and click Add Product.

  4. In Product Setup, for Facebook Login, click Set Up. This brings up the Quickstart for Facebook Login. Skip the Quickstart.

  5. Instead, in the left-hand navigation menu, under Products > Facebook Login, click Settings.

  6. Under Valid OAuth redirect URIs, add the following entry:

    https://stitch.mongodb.com/api/client/v1.0/auth/callback
    
  7. Save changes.

See Facebook Authentication for more information.

2

Retrieve the App ID and App Secret for your Facebook app.

  1. Click Settings for your Facebook application (i.e. not the Settings under Facebook Login).
  2. Note the App ID and App Secret. You will use the information in the Authentication section of the MongoDB Stitch Admin Console.
3

Configure MongoDB Stitch for Facebook Authentication.

  1. Click Authentication in the left side navigation in the MongoDB Stitch console.

    The Authentication page displays the Authentication Providers information.

  2. For Facebook, click the Edit button.

  3. In the Edit Provider dialog,

    • Switch Facebook to enabled.

    • Enter your new Facebook App ID in the Client ID field and Facebook App Secret in Client Secret field.

    • In the Redirect URIs, add the following:

      Important

      Enter the URI exactly, including the trailing slash /.

      http://localhost:3000/
      
    • In the Metadata Fields, select name and email.

  4. Click Save.

D. Set Up Google Auth

Estimated Time to Complete: 10 minutes

1

Set up a project in Google Cloud Platform.

  1. Log into your Google Cloud Platform (GCP) account. If you do not already have a GCP, create one by visiting https://cloud.google.com/.
  2. Open the GCP console.
  3. Select your preferred organization. If you have not yet created an organization in your GCP account, you must create one now.
  4. Create a new project for your MongoDB Stitch application, named ToDo-Web. See Creating and Managing Projects for instructions.
2

Create OAuth Credentials

  1. Select API Manager from the left-hand navigation bar, then select Credentials. Ensure that the ToDo-Web project is selected as the active project

  2. Select Create Credentials, then select OAuth client ID. Configure the credentials as follows:

    • For Application Type, select Web application.

    • For Name, enter the name you want to associate with this application.

    • For Authorized JavaScript origins, enter the following:

      https://stitch.mongodb.com
      
    • For Authorized redirect URIs, enter the following:

      https://stitch.mongodb.com/api/client/v1.0/auth/callback
      
  3. Click Create to create the credentials. Note the Client ID and Secret, as you need them in the following step.

3

Configure MongoDB Stitch for Google Authentication

  1. From the MongoDB Stitch user interface, click Authentication in the left side navigation.

    The Authentication page displays the Authentication Providers information.

  2. For Google, click the Edit button.

  3. In the Edit Provider dialog,

    • Switch Google to enabled.

    • Enter the Client ID and Client Secret from the OAuth credentials you created in the previous step.

    • For Redirect URIs, add the following:

      Important

      Enter the URI exactly, including the trailing slash /.

      http://localhost:8001/
      
    • In the Metadata Fields, select Name and Email.

  4. Click Save.

E. Download the ToDo Application

Estimated Time to Complete: 2 minutes

Download from the MongoDB Stitch github example repository and unzip. The source code for the ToDo application can be found in todo directory.

F. Set Up and Run the ToDo Application

Estimated Time to Complete: 5 minutes

1

Retrieve your MongoDB Stitch App ID.

To find your App ID, in MongoDB Stitch console, go to Clients view. Click Copy App ID to copy your application ID.

2

Update index.js with your App Id.

In the todo/src/ directory, open index.js in an editor and update the appId variable with your MongoDB Stitch app id.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import React from 'react';
import { render } from 'react-dom';
import { StitchClient } from 'stitch';
import { browserHistory, Route } from 'react-router'
import { BrowserRouter, Link } from 'react-router-dom'

require("../static/todo.scss")

let appId = 'STITCH-APP-ID';
...
3

Review code to connect to MongoDB Stitch.

Use the StitchClient class to connect to your MongoDB Stitch application.

The src/index.js file has the following code:

let stitchClient = new StitchClient(appId, options);
4

Review code to authenticate application users.

StitchClient provides various functions to authenticate. This tutorial uses StitchClient.authWithOAuth("<provider>") to authenticate with Facebook or google.

<div className="login-links-panel">
  <h2>TODO</h2>
  <div
    onClick={() => this.props.client.authWithOAuth("google")}
    className="signin-button"
  >

  ...

    <span className="signin-button-text">Sign in with Google</span>
  </div>
  <div
    onClick={() => this.props.client.authWithOAuth("facebook")}
    className="signin-button"
  >
    <div className="facebook-signin-logo" />
    <span className="signin-button-text">
      Sign in with Facebook
    </span>
  </div>
</div>
5

Review code to access the MongoDB service and collections.

To access MongoDB database and collection using the MongoDB service, use:

For example, in the project, the index.js file has the following code:

let stitchClient = new StitchClient(appId, options);
let db = stitchClient.service("mongodb", "mongodb-atlas").db("todo");
let items = db.collection("items");
let users = db.collection("users");
6

Review code to perform CRUD operations on the collection.

Create a Document

The ToDo application uses the Collection.insert to create documents in MongoDB:

items.insert([{ text: event.target.value, owner_id: stitchClient.authedId() }]).then(() => { ... });

Note that the inserted document uses StitchClient.authedId() to retrieve the authenticated client’s user ID and saves that value to the owner_id field. This ensures that MongoDB Stitch allows the write based on the rules and filters configured for todo.items.

Retrieve a Document

The ToDo application uses the Collection.find method to retrieve documents from MongoDB:

items.find(null, null).then(function(data) { ... });

Note that there is no query predicate nor projection specified. The configured MongoDB Stitch rules and filters ensures that the operation only returns those documents whose owner_id field matches the user ID of the client issuing the operation.

Update a Document

The ToDo application uses the Collection.updateOne to update documents in MongoDB:

items.updateOne({ _id: id }, { $set: { checked: status } }).then(() => { ... }, ... );
Delete a Document

The ToDo application uses Collection.deleteMany to delete documents in MongoDB:

items.deleteMany({ checked: true }).then(() => { ... });
7

Install application dependencies.

Run the following command from the todo directory:

npm install
8

Start the application.

Substitute your App ID in the following command and run from the todo directory:

APP_NAME=<App ID> npm start
9

Open a browser to http://localhost:8001/ to access the ToDo app.

  1. Sign in with Google or Facebook credentials, depending on which providers you configured during this procedure.
  2. Enter the todo item in the text box to add the item to the list.
  3. You can check the boxes to mark the item as complete.
  4. If you have marked items as complete, you can click on the clean up button to delete completed items.
10

Configure the MongoDB service.

  1. Click on the MongoDB service mongodb-atlas.

  2. In the Rules tab, add the following collection:

    Database: todo

    Collection: items

    Note

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

The application saves document to the collection. Each document in the todo.items collection has the form:

{
  "_id" : <ObjectID>,
  "text" : <string>,      // ToDo item.
  "owner_id" : <string>,  // Corresponds to the user logged into the app.
  "checked" : <boolean>   // Optional.  Only appears if user checks the item in the app.
}
11

Review the rules for todo.items collection.

Click on todo.items to view the read rules, write rule, the validation rule, and the filter rule.

MongoDB Authorization

MongoDB Stitch rules do not override the read and write access (i.e. authorization) that may have been set up separately in MongoDB. That is, MongoDB Stitch rules determine whether the fields are readable or writable; not whether the client has authorization to read or write to a particular database or collection.

Similarly, MongoDB Stitch validation rules do not override document validation rules set up separately in MongoDB.

Read Rule

To view the read rule, click on the R in the Field Rules view.

To view the read rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following read rule for the top-level document:

{
  "owner_id": "%%user.id"
}

With this rule, read and write operations can access all fields in a document if the document contains an owner_id field whose value equals the user ID (%%user.id) of the client issuing the read. If the owner_id field in the document does not equal the client user id, no field in the document is readable.

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

Write Rule

To view the write rule, click on the W in the Field Rules view.

To view the write rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following write rule for the top-level document:

{
  "owner_id": "%%user.id"
}

With this rule, the write operation must result in a document where the owner_id equals the user ID of the client issuing the write. If the value of owner_id does not match the client user ID, MongoDB Stitch blocks the write.

Modify the write rule to the following and click Save:

{
  "%or": [
    { "%%prevRoot.owner_id": "%%user.id" },
    { "%%prevRoot": { "%exists": 0 } }
  ]
}

%%prevRoot references the original document before the write operation. This rule requires that either:

  • The document to be modified by the write operation contains an owner_id field that equals the id of the user logged in to the ToDo app (%%user.id)

- or -

  • The document to be modified by the write operation did not exist; i.e. the write operation results in an insert operation.

For more information on MongoDB write rules, see MongoDB Service Write Rule.

Validation Rule

To view a validation rule, if any, click on a V in the Field Rules view.

To view a validation rule, click on the owner_id in the Field Rules view.

By default, the collection has the following validation rule specified on the owner_id field that determines whether a write operation is permissible:

{
  "%or": [
    { "%%prev": "%%user.id" },
    { "%%prev": { "%exists": false } }
  ]
}

With this rule, a write operation is valid if either:

  • The write operation modifies a document where the value of owner_id previous to the write operation (%%prev) equals the user ID (%%user.id) of the client issuing the write. An example of this kind of write operation is a client modifying a document that it previously inserted, or
  • The write operation modifies a document where there was no value for the owner_id field (%exists) previous to the write operation (%%prev). An example of this kind of write operation is an insert of a new document.

Modify the validation rule to the following and click Save:

"%%user.id"

The new rule requires owner_id to equal the id of the user logged in to the ToDo app (%%user.id). MongoDB Stitch prevents write operations that fail this rule.

For more information on validation rules, see MongoDB Service Validation.

Allow All Other Fields

By default, Allow 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 Allow All Other Fields to control the shape of the documents. For more information, see MongoDB Service Rules

Filters

Click on the Filters.

By default, the collection has the following filter rule:

When Match Expression
{ "%%true": true } { "owner_id": "%%user.id" }

This filter indicates that when %%true equals true (i.e. always), apply the following filter { "owner_id": "%%user.id" } to the read and write operations. This filter is in addition to the query predicates for read and write operations.

For more information on filters, see MongoDB Service Filters.

Collection Information

Each document in the todo.items collection has the form:

{
  "_id" : <ObjectID>,
  "text" : <string>,      // ToDo item.
  "owner_id" : <string>,  // Corresponds to the user logged into the app.
  "checked" : <boolean>   // Optional.  Only appears if user checks the item in the app.
}

Next Steps

To integrate the ToDo app with Twilio, see Integrate ToDo with Twilio.