Most apps and websites contain much functionality that’s tedious to implement and has been done thousands of times before. MongoDB Stitch takes care of a lot of these chores – for example, making it simple to interact with third-party APIs. This post explains how I used Stitch to do just that that this week.

I recently described how I ported my legacy website to Stitch. After reading that post, one of our Paris Solution Architects spotted that there was a bug in how I was validating phone numbers in my forms (specific to France’s dialling plan). I was about to go into my code to tweak the regular expressions to cope with French phone numbers. However, what if there was another country with odd rules? What if the rules changed?

It then struck me that this is precisely the kind of chore that I should use Stitch to replace – being an expert in regular expressions and country-specific dialling plans wasn’t going to make the experience any better for my users, and so I should contract it out to “someone” else.

A quick Google later, and I’d settled on the NumVerify service which provides an API to validate phone numbers and add some extra information such as the type of line and the same number in full international format.

To access the NumVerify API, I needed to create a Stitch HTTP service. I named the service apiplayer.net and created a rule to allow the service to access the required domain (apiplayer.net) using GET requests:

Then I can call use that service from a new Stitch Function (verifyPhoneNumber):

NumVerify is as flexible as possible in accepting phone numbers in different formats. It also sets the resulting international_format field to a fully formatted international number – I use that to replace the user-provided number in the form, ensuring that all numbers stored in Atlas are in the same format. In one swoop, I’ve ripped out my spaghetti regular expression code, made the validations more robust, and added a new feature (normalizing the phone numbers before I store them) – result!

See the results at stitch.oleronvilla.com, but please don’t judge my code, I still need to delegate a lot more to Stitch and other services!

From the start, Stitch has been great at serving up dynamic content and interacting with backend services. There was just one piece missing that meant that you still needed an app server or hosting service – storing and serving up your static assets (index.html, style.css, logo.png, etc.). The recent addition of Stitch Hosting, currently in beta, fixes that!

Following the dogfooding principle, I decided to try porting one of my existing websites to Stitch (the site is for renting out our holiday home). Now, this isn’t some newfangled website with all the latest bells and whistles. I’d built the original site before the serverless and mobile-first movements took off; using PHP in the backend and JavaScript/JQuery in the frontend. The vast majority of the porting effort went into replacing the backend PHP code with frontend JavaScript. Once that was done, porting it to Stitch was a breeze.

Step 1 was to enable Hosting through the Stitch UI and upload the (907) static files. You can upload all the files manually through the UI, but here’s a pro-tip, you can perform a bulk upload using the Stitch CLI:

stitch-cli import --include-hosting --strategy=replace

When I made further edits, I used the Stitch UI to upload the modified files:

When users submitted forms on the original site, I was sent an email via GoDaddy’s temperamental gdform.php script (which writes the data to a local file, which GoDaddy’s cron job may eventually process to send the email), and I was looking forward to ripping that out and using Stitch QueryAnywhere instead. The frontend code to store the data in MongoDB is straightforward:

So that safely stores the user-submitted data in MongoDB. The next step was to bring the site into the 1990s by having it send me a text message with the submitted data. I could have gone back to the frontend code to send the data to a Stitch Function (in addition to writing it to Atlas), but, as my legacy frontend code is somewhat ‘fragile’, I prefer to make as few changes there as possible. Stitch Triggers to the rescue! I created a new Stitch Function (textReservation) to send the form data to Twilio:

Stitch has simple, built-in integration with AWS services, letting you call services like Kinesis from Stitch Functions using syntax similar to the AWS SDK. To start, we configure a new AWS service in Stitch using an IAM role from AWS and then create a new Stitch Service rule to enable Kinesis:

We then need a Stitch Function (kinesisTrigger) to put our rover’s sensor data onto a Kinesis stream. Note that the sensor data is taken from the event function argument (we’ll get to that in a second):

As the rover will sometimes be disconnected from the network, it stores the readings locally in the MongoDB Mobile database. Stitch Mobile Sync will then sync these same documents to Atlas whenever it’s online.

We’ve configured the kinesisTrigger trigger to fire whenever a new document is added to the rover.sensors collection. The trigger calls the linked function KinesisTrigger (the trigger and function names don’t need to match), passing the inserted document as a function argument. From the time that the Stitch Trigger is hit, it typically takes just 20ms to get the data into Kinesis.

This completes the blog series. As a reminder, this is what we’ve covered in the five posts:
– MongoDB Stitch/Mobile Mars Rover Lands at AWS re:Invent describes how MongoDB Stitch, MongoDB Mobile, Atlas, Android Things, a Raspberry Pi, and Amazon Kinesis are used to reliably control our Mars rover.
– MongoDB Stitch QueryAnywhere focuses on how the Mission Control app records the user commands in MongoDB Atlas by calling the Stitch SDK directly from the frontend code.
– MongoDB Stitch Mobile Sync shows how Stitch Mobile Sync synchronizes the user commands written to MongoDB Atlas by the Mission Control app with the MongoDB Mobile database embedded in the rover (and how it syncs the data back to Atlas when it’s updated in MongoDB Mobile).
– MongoDB Stitch Functions focuses on how a Stitch Function is used to provide aggregated sensor data such as the average temperature for the last 5 minutes.
– MongoDB Stitch Triggers & Amazon Kinesis shows how we use MongoDB Stitch Triggers and the Stitch AWS service to push MongoDB database changes to Amazon Kinesis.

This is the fourth in a series of blog posts examining how the MongoDB Mobile/Stitch-controlled rover was put together for our re:Invent demo. This post focuses on how a Stitch Function is used to provide aggregated sensor data such as the average temperature for the last 5 minutes.

A common question we were asked at re:Invent is how Stitch’s serverless Functions compare with AWS Lambda functions. Stitch functions are designed to be very light-weight (run as Goroutines and deliver low latency – ideal, for example, when working with a database (especially as your function has a persistent MongoDB connection). In contrast, Lambda functions are more heavy-weight (Lambda spins up containers to run your functions in) – better suited to compute-heavy operations.

You write your functions in JavaScript (ES6) through the Stitch UI or the command line. We created this function (getReadings) to fetch a rover’s sensor data for the specified interval and then return the computed average, minimum, and maximum values:

There’s a lot more that you can do in functions, such as sending data to another cloud service. You’ll see an example of this in the next post which shows how a Stitch Trigger calls a Stitch function to send MongoDB Atlas data to AWS Kinesis.

Many people who took part in the demo at re:Invent asked why Mission Control wrote the commands to Atlas rather than sending them directly to the rover. The reason is that you can’t guarantee that the rover will always have network access (and when thousands descended on the expo hall for the Monday evening social, we learned that maintaining a connection over conference WiFi can be just as tricky as maintaining one to Mars). The commands are stored in Atlas and then synchronized to the rover whenever it’s online.

Each rover has a single document in the rover.rovers collection, and each command is stored as an element in the moves array:

Stitch Mobile sync automatically pushes the document to the rover’s MongoDB Mobile database, and the rover’s Android app moves the rover in response. Once a move command has been acted on, the app removes it from the array and updates the document in MongoDB Mobile. Stitch Mobile Sync then automatically pushes the change back to Atlas:

You may have noticed that the same document is being updated in both Atlas and MongoDB Mobile, raising the possibility of conflicts. A conflict occurs when the document is updated in one database and, before that change has been synced, the same document is updated in the second. Sketchy network connectivity increases the size of the window where this can happen and that makes conflicts more likely.

Fortunately, Stitch Mobile Sync allows the client application to register a conflict handler function. The function is passed both versions of the document and can decide what the ‘winning’ document should look like. The conflict handling could be as simple as “local wins”, but in this case, we take the remote document (which contains at least one command not yet added to the local database) and remove any commands that have already been acted on:

public class RoverActivity extends Activity
implements ConflictHandler<Rover> {
@Override
public Rover resolveConflict(
final BsonValue documentId,
final ChangeEvent<Rover> localEvent,
final ChangeEvent<Rover> remoteEvent
) {
if (localEvent.getFullDocument().getLastMoveCompleted() == null) {
return remoteEvent.getFullDocument();
}
// Given this sync model consists of a single producer and a
// single consumer, a conflict can only occur when a production
// and consumption happens at the same "time". That means
// that there should always be an overlap of moves during a
// conflict and that the last move completed is always present
// in the remote. Therefore we should trim all moves up to
// and including the last completed move.
final Rover localRover = localEvent.getFullDocument();
final String lastMoveCompleted = localRover.getLastMoveCompleted();
final Rover remoteRover = remoteEvent.getFullDocument();
final List<Move> nextMoves = new ArrayList<>(remoteRover
.getMoves().size());
boolean caughtUp = false;
for (final Move move : remoteRover.getMoves()) {
if (move.getId().equals(lastMoveCompleted)) {
caughtUp = true;
} else
{
if (caughtUp) {
nextMoves.add(move);
}
}
}
return new Rover(localRover, nextMoves);
}
}

The next post in this series looks at how Stitch Functions can be used to provide an aggregated view of the rover’s sensor data.

At AWS re:Invent, we demonstrated how MongoDB Mobile, MongoDB Stitch, and AWS services could be used to build a cloud-controlled Mars rover – read the overview post for the setup. This post focuses on how the mission control app records the user commands in MongoDB Atlas.

Mission Control is a simple web application that we ran on an iPad. The web app takes commands from the user through its UI which displays directions for the rover to travel in. Each command sets the rover off in that direction for a short fixed amount of time.

Rather than sending the command directly to the rover, and as Mars is a long way away and network connections are not always reliable, the app stores the commands in an array within the rover’s document in Atlas – in that way, commands can be queued up and sent to the rover as soon as it’s back online.

This is what the document looks like after a few commands have been submitted (but not yet acted on by the rover):

A traditional way of access the database from the frontend app would be to stand up an app server, implement a custom REST API and data access control layer, and then send the commands to it from the frontend app. MongoDB Stitch massively simplifies that workflow by letting a web (or mobile) app execute MongoDB Query Language operations directly – removing the need for thousands of lines of boilerplate code.

When we explained this access model to demo visitors, some were nervous about this approach as we’ve been taught that the schema and database access should be hidden from the frontend (remember SQL injection attacks?). Fortunately, Stitch QueryAnywhere is made up of two components – the first is the Stitch SDK that enables direct access to the database, the second is the sophisticated, fine-grained user access controls provided by the Stitch service. If that doesn’t allay your fears then you have the option to obfuscate the schema by accessing the database through Stitch Functions.

Updating the document from the web app is a cinch with Stitch. The first step is to import the Stitch SDK:

If you are used to working with the MongoDB Query Language from an app server, that should seem very familiar. The only thing that might catch your eye is that __stitch_sync_version.v. That’s part of how this update will get to the MongoDB Mobile database embedded in the rover. We’ll explain that in the next part.

Powered by MongoDB Mobile, MongoDB Stitch, and AWS Kinesis, the MongoDB rover debuted at AWS re:Invent. More than a thousand people stopped by our demo to see if they could navigate the rover around a treacherous alien landscape.

One of the challenges in controlling a rover on the other side of the Solar System is that there will frequently be times when you lose connectivity. To solve that, we store all of the commands in MongoDB Atlas and sync them to the rover (in its local MongoDB Mobile database) whenever it’s contactable.

After the commands are sent to the cloud, Stitch Mobile Sync takes over, ensuring all commands are automatically written to the MongoDB Mobile database embedded on the rover (running Android Things on a Raspberry Pi 3b) by Stitch Mobile Sync. The Java app on the rover then acts on the synced commands (moving the Rover), before removing them from the mobile database to reflect that it’s completed with that set of commands – with the updated status then finally synced back to Atlas by Stitch Mobile Sync.

The rover can also record environmental sensor data in MongoDB Mobile, which Stitch Mobile Sync syncs to the sensors collection in Atlas. A Stitch Trigger on the sensors collection then runs a Stitch Function to push those sensor readings to AWS Kinesis for further analysis, such as anomaly detection.

The first appearance of the MongoDB rover coincided with the Mars landing of InSight. We even had our own 7 minutes of terror when the event WiFi buckled under the pressure of thousands of delegates descending on the expo hall during Monday’s evening social – but it did at least demonstrate that Stitch Mobile Sync quickly catches up once connectivity is restored.

This post is the first in a series delving into the components of this interactive demo, and if you can’t wait for more details, then you can find all of the code in GitHub.

For those new to MongoDB Stitch, it’s the serverless platform from MongoDB that isolates complexity and ‘plumbing’ so you can build applications faster. Stitch went GA in June 2018, and we recently added a set of new capabilities, including global Stitch apps, more AWS services, a React Native SDK, and the beta for Stitch Mobile Sync. MongoDB Mobile is an embedded version of the MongoDB database that you can embed in your mobile or IoT apps.

You can also invoke your Stitch functions through the mongo shell. To do that, you’ll need to enable the MongoDB wire protocol so that the shell can talk to your Stitch app, then use the Stitch connection string provided. Once connected, you can call Stitch functions explicitly like this:

Is MongoDB Mobile + Stitch Mobile Sync the same as a cache in a progressive app?

It certainly removes the need to have a separate cache, but it does much more. With MongoDB Mobile, the data is persistently stored on your device. You also have the full power of the MongoDB Query Language to perform sophisticated queries and aggregations on that local data. Changes made to the local database are pushed back to MongoDB Atlas, and from there to any other mobile devices configured to sync the same documents (e.g., for the same user running the app on another device).

How do I download & embed MongoDB Mobile?

You simply need to add 1 line to your Android or Xcode project to have access to the entire Stitch SDK, including the Stitch Local Database service (i.e.,the MongoDB Mobile database). The Stitch SDK includes the entire mobile and makes it very easy to use and consume, even if you’re just using the local MongoDB Mobile database and not Stitch.

If you are developing an app using Java, Swift, or JavaScript then the Stitch SDK is the best way to access MongoDB Stitch from your frontend application code – getting to your data and accessing your Stitch Services and Functions becomes child’s play.

But, what if you are developing in another language – perhaps running on an app server? Luckily, MongoDB Stitch now supports the MongoDB wire protocol – meaning that you can continue to work with your favorite MongoDB drivers (such as PyMongo) and tools such as the mongo shell.

After enabling connection string access, connecting to your Stitch app from your application is business as usual – just use the connection string you’re shown in the Stitch UI (replacing the username and password with one of your existing Stitch users). This example is for Python, but the pattern is the same for other languages:

The Stitch SDK is the best way to access MongoDB Stitch from your frontend application code – getting to your data and accessing your Stitch Services and Functions becomes child’s’ play.

However, those already using MongoDB may have existing backend code and tools that work with MongoDB. MongoDB Stitch now supports the MongoDB wire protocol – meaning that you can continue to work with your favorite tools (including the mongo shell) and drivers while benefiting from Stitch’s quick and simple data access control and hosted JavaScript functions.

After enabling connection string access, connecting to your Stitch app from the mongo shell is business as usual – just use the connection string you’re shown in the Stitch UI: