Build your own Realtime Database with Socket.io and MongoDB

Teyyihan Aksu
The Startup
Published in
4 min readJun 15, 2020

--

Hey there! As the title says, we will build our realtime database. But why? There are already services like Firebase, right? And it’s easy to build apps with Firebase. Well, it is as expensive as its ease. There’s an article that is about how expensive it can get here.

I was going to build an android app and that app needs realtime interactions. So I started to search. There are a couple of options. But because of its simplicity, I’ve chose socket.io for Websocket and MongoDB for storage.

So let’s start!

I’ll be coding in Visual Studio Code for server side and Android Studio for android (client) side. First thing we need to do is create a project. Then we will open the built-in terminal and type:

npm init

This will generate a package.json file, looks like this:

package.json

After that we will install libraries we need. They are:

  1. Socket.io
  2. Mongoose (for MongoDB)
  3. Express
  4. Body-parser (to read objects)

To install those, we simply type:

npm install express body-parser socket.io mongoose

Now it’s time to create our collection ( like tables in SQL ). I will create a user object that has id, name and age.

To achieve this, i created a UserModel.js file. It looks like this:

Then we need to create our database. But there is a problem. We can’t create a database directly and hope it works. Because it won’t work. Why? Because we will be watching the database. Mongodb wants us to create a Replica Set . There is tutorial from their website here.

Finally we can create our server.js file. We will connect to database, get the sockets and respond to sockets here.

First, import the dependencies:

Now we need to connect to our database:

If there will be an error while connecting to database, we will be notified.

We need to welcome our sockets, aren’t we? Clients can emit an event and we will get the sockets when they connected to server. In this example I will emit a joinRoom event from client side and will be listening on server side.

When they connected, we will join them in a room with their id. Room is a part of Socket.io and explained here.

Now, we’ve set everything except listening for changes in our database. Let’s listen then! Inside mongoDB connection callback we will add this:

Watch() is part of MongoDB and it’s great for realtime interactions. Whenever change happens, this method will run and we will emit the changes on changes event. As you remember, we did join the clients with their ids. Now we can emit the message to specific rooms. You will see the example soon.

That’s it for the server side. Let’s move on to client side.

First we need to add the library

implementation 'com.github.nkzawa:socket.io-client:0.6.0'

Then go to your manifest.xml and add this to your application tag:

android:usesCleartextTraffic="true"

Then we will connect to our socket server:

socket = IO.socket("http://192.168.1.2:3100");
socket.connect()

I will create a dummy JSON and emit it.

val jsonString = "{myID: '123123'}"
try {
val jsonData = JSONObject(jsonString)
socket.emit("joinRoom", jsonData)
} catch (e: JSONException) { }

Let’s start to listen:

socket.on("changes", {
it
.forEach {
Log.d(TAG, "onchange: "+it)
}
}
)

I inserted a user to my database using MongoDB Compass ( GUI for your databases)

Example data

Now I’ll first run the server and then client. Then I’ll update the example data and we will see it on the client’s log.

User joined room

Test time!

Congratulations! You created your own realtime database. You can go more complex with this to achieve your goals. Stay safe!

Codes for this article:

Android : https://github.com/teyyihan/Medium_SocketIO_Android

NodeJS : https://github.com/teyyihan/Medium_SocketIO_Server

--

--