How To Write A Simple Node.js/MongoDB Web Service for an iOS App

Learn how to create a simple Node.js and MongoDB web service for an iOS app in this tutorial. By Michael Katz.

Leave a rating/review
Save for later
Share
Note: If you’d like to create your web service in Swift, check out our Kitura tutorial Getting Started With Server-side Swift

In today’s world of collaborative and social apps, it’s crucial to have a backend that is simple to build and easy to deploy. Many organizations rely on an application stack using the following three technologies:

This stack is quite popular for mobile applications since the native data format is JSON which can be easily parsed by apps by way of Cocoa’s NSJSONSerialization class or other comparable parsers.

In this tutorial you’ll learn how to set-up a Node.js environment that leverages Express; on top of that platform you’ll build a server that exposes a MongoDB database through a REST API, as such:

The backend database rendered in a HTML table

The backend database rendered in a HTML table

The second part of this tutorial series focuses on the iOS app side. You’ll build a cool “places of interest” app to tag interesting locations so that other users can find out what’s interesting near them. Here’s a sneak peek at what you’ll be building:

The TourMyTown main view

The TourMyTown main view

This tutorial assumes that you already know the basics of JavaScript and web development but are new to Node.js, Express, and MongoDB.

A Case for Node+Mongo

Most Objective-C developers likely aren’t familiar with JavaScript, but it’s an extremely common language among web developers. For this reason, Node has gained a lot of popularity as a web framework, but there’s many more reasons that make it a great choice as a back-end service:

  • Built-in server functionality
  • Good project management through its package manager
  • A fast JavaScript engine, known as V8
  • Asynchronous event-driven programming model.

An asynchronous programming model of events and callbacks is well suited for a server which has to wait for a lot of things, such as incoming requests and inter-process communications with other services (like MongoDB).

MongoDB is a low-overhead database where all entities are free-form BSON — “binary JSON” — documents . This lets you work with heterogeneous data and makes it easy to handle a wide variety of data formats. Since BSON is compatible with JSON, building a REST API is simple — the server code can pass requests to the database driver without a lot of intermediate processing.

Node and MongoDB are inherently scalable and synchronize easily across multiple machines in a distributed model; this combination is a good choice for applications that don’t have an evenly distributed load.

Getting Started

This tutorial assumes you have OS X Mountain Lion or Mavericks, and Xcode with its command line tools already installed.

The first step is to install Homebrew. Just as CocoaPods manages packages for Cocoa and Gem manages packages for Ruby, Homebrew manages Unix tools on Mac OS X. It’s built on top of Ruby and Git and is highly flexible and customizable.

If you already have Homebrew installed, feel free to skip to the next step. Otherwise, install Homebrew by opening Terminal and executing the following command:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
Note: cURL is a handy tool to send and receive files and data using URL requests. You use it here to load the Homebrew installation script — later on in this tutorial you’ll use it to interact with the Node server.

Once Homebrew is installed, enter the following command in Terminal:

brew update

This simply updates Homebrew so you have the most up-to-date package list.

Now, install MongoDB via Homebrew with the following command:

brew install mongodb

Make a note of the directory where MongoDB is installed as shown in the “Summary” output. You’ll need this later to launch the MongoDB service.

Download and run the Node.js installer from http://nodejs.org/download/.

Once the installer has completed, you can test out your Node.js installation right away.

Enter the following command in Terminal:

node

This puts you into the Node.js interactive environment where you can execute JavaScript expressions.

Enter the following expression at the prompt:

console.log("Hello World");

You should receive the following output:

Hello World
undefined

console.log is the Node.js equivalent of NSLog. However, the output stream of console is much more complex than NSLog: it has console.info, console.assert, console.error among other streams that you might expect from more advanced loggers such as CocoaLumberjack.

The “undefined” value written to the output is the return value of console.log — which has no return value. Node.js always displays the output of all expressions, whether the return value is defined or not.

The global object has all the pre-defined constants, functions, and datatypes available to programs running in the Node.js environment. Any user-created variables are added to the global context object as well. The output of global will list pretty much everything accessible in memory.

Note: If you’ve worked with JavaScript before, you need to be aware that there are a few differences between the Node.js environment and the browser environment. The global object is called global instead of window. Typing global and pressing enter at the Node.js interactive prompt displays all the methods and objects in the global namespace; however it’s easier to just use the Node.js documentation as a reference. :]

Running a Node.js Script

The interactive environment of Node.js is great for playing around and debugging your JavaScript expressions, but usually you’ll use script files to get the real work done. Just as an iOS app includes Main.m as its starting point, the default entry point for Node.js is index.js. However, unlike Objective-C there is no main function; instead, index.js is evaluated from top to bottom.

Press Control+C twice to exit the Node.js shell. Execute the following command to create a new folder to hold your scripts:

mkdir ~/Documents/NodeTutorial

Now execute the following command to navigate into this new folder and create a new script file in your default text editor:

cd ~/Documents/NodeTutorial/; edit index.js

Add the following code to index.js:

console.log("Hello World.");

Save your work, return to Terminal and execute the following command to see your script in action:

node index.js

Once again, there’s the familiar “Hello World” output. You can also execute node . to run your script, as . looks for index.js by default.

node_run

Admittedly, a “hello world” script does not a server make, but it’s a quick way to test out your installation. The next section introduces you to the world of Node.js packages which will form the foundation of your shiny new web server!