Build a PWA with MongoDB

I’ve always liked tutorials that show you practical examples. They help understand how to use code to actually build apps in production environment. Then I could take that knowledge to build my own.

In this tutorial we will store world geolocation data in a Mongo collection.

Open the live demo of this tutorial at infinitesunset.app.

What Is Mongo?

The name Mongo was taken from the word Hu_mongo_us.

In the context of storage it can mean dealing with large quantities of data. And that’s what databases are pretty much for. They provide you with an interface to create, read, edit(update) and delete large sets of data (such as user data, posts, comments, geo location coordinates and so on) directly from your Node.js program.

By “complete” I don’t mean documentation for each Mongo function. Rather, an instance of Mongo code used as a real-world example when building a PWA.

A Mongo collection is similar to what a table is in a MySQL database. Except in Mongo, everything is stored in a JSON-like object. But keep in mind that it also uses BSON to store unique _id property, similar to how MySQL stores unique row key.

Installing Mongo And Basic Operations

In the Terminal on Mac or bash.exe on Windows 10, log in to your remote host with ssh root@xx.xxx.xxx.xx (replace the x’s with your web host’s IP address.) Then use cd to navigate to your project directory on the remote host, for example, /dev/app.

Install the system-wide Mongo service:

sudo apt-get install -y mongodb

The -y directive will automatically answer “yes” to all installation questions.

We need to start the Mongo service after this (explained in next section.)

Mongo Shell

Just like MySQL has a command line shell where we can create tables, users, and so on, Mongo also has its own shell to create collections, show databases, and more.

First we need to start theMongo service:

sudo service mongodb start

If you ever need to stop theMongo server, you can do that with:

sudo service mongodb stop

But don’t stop it – we need the service running for the next part!

To enter the Mongo shell, type the mongo command into your cli/bash:

mongo

You will see your bash change to a > character. Let’s type the use command to create a new (or switch to an existing) database:

> use users
switched to db users

Type > db to verify that we indeed switched to users database:

> db
users

Let’s take a look at all existing databases by executing the show dbs command:

> show dbs
admin  0.000GB
local  0.000GB

Even though we created a users database in the earlier step, it’s not on this list. Why? That’s because we haven’t added any collections to the database. This means that users actually exists, but it won’t be shown on this list until a collection is added.

Adding Mongo Collection

Let’s add a new collection to users database. Remember a collection in Mongo is the equivalent of a table in MySQL:

db.users.insert({name:"felix"})

We just inserted a collection into the users database.

Let’s run > show dbs now:

> show dbs
admin  0.000GB
local  0.000GB
users  0.000GB

Simply inserting a JSON-like object into the users database has created a “table.” But in Mongo, it’s just part of the document-based model. You can insert more objects into this object and treat them as you would rows/columns in MySQL.

Installing the Mongo NPM Package

npm install mongodb --save

Generating The Data

Before we go over Mongo methods, let’s decide what we want to store in the database Let’s take a look at world coordinate system. It’s quite different from Cartesian. The central point here is located relatively near Lagos, Nigeria:

Latitude and Longitude visualized. [0,0] point is located in the center of the coordinate system with axis going left and down in negative direction. HTML5 geo location will take care of calculating your location automatically based on your IP address. But we still need to convert it to 2D on the image.

Front-End

Collecting the data.

HTML5 provides an out-of-the-box geo location system and gives us latitude and longitude, as long as the client agrees to share that information. The following code will create a pop up message box on desktop and mobile devices asking users to “allow” the browser to share its location. If user agrees, it will be stored in lat and lon variables:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        let lat = position.coords.latitude;
        let lon = position.coords.longitude;
    }
}

Well, that’s a great start.

But this isn’t enough. We need to convert it into a 2D coordinate system that HTML5 <canvas> understands. We need to draw location markers on top of the map image! So I wrote this simple World2Image function that takes care of that:

function World2Image(pointLat, pointLon) {
    const mapWidth = 920;
    const mapHeight = 468;
    const x =  ((mapWidth / 360.0) * (180 + pointLon));
    const y =  ((mapHeight / 180.0) * (90 - pointLat));
    return [x, y];
}

We simply divide map image dimensions by 360 and 180 respectively and then multiply them by 180 + pointLong and 90 - pointLat to adjust to the center. And our final code that converts latitude/longitude to 2D coordinates will look like this:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        let lat = position.coords.latitude;
        let lon = position.coords.longitude;
        let xy = World2Image(lat, lon);
        let x = xy[0];
        let y = xy[1];
    }
}

In your app of course you can use any data you want. We just need a meaningful set to demonstrate a practical example for a potential live sunset photography app.

Place the code above between

#pwa #mongodb #node-js #express #web-development

Build a PWA with MongoDB
27.60 GEEK