« Back to Blogs

Real-Time Updates Using Pusher in MongoDB and React

Real-Time updates in MongoDB and react

This guide is for developers who already know the basics of React and MongoDB, and who want to learn real-time updates in MongoDB in a simple few steps.

Before starting about this topic, lets quickly learn what's MongoDB and react in brief:

React: It’s a front end Open source Javascript library for developing Single page web applications built by Facebook.

MongoDB: It’s no structured database, it uses JSON like documents with optional schemas.

MongoDB has a disadvantage in that it is not giving real-time updates, so we can figure out how to do the real-time updates in MongoDB

Let’s learn what Pusher is and How to use it with MongoDB.

What is Pusher?

Pusher is a powerful full cloud service, for developers APIs and libraries that help you add rich real-time features in minutes.

How to Use it with MongoDB?

Let’s create a custom web application and by using that we can understand real time updates in mongo db.

Flow:

  • We can create a channel in the pusher, which provides real-time communication between the app and the server
  • From the server, we publish an event, which is subscribed by the app. (Ex. We create an event called inserted, and when we add some data using this event from the server, the app knows that some data is pushed so it will receive the data which is pushed)

Prerequisite:

  • Node JS development environment Provide you a link to set up Node JS in your machine. Simply download and install the node as per your system. (https://nodejs.org/en/download/)
  • Basic Knowledge of MongoDB and React

Setup:

  • Setup the Backend for getting the configuration for the project:
    • Create an Account on Pusher.com
    • Create a Channel in Pusher. Now you think about what is Channel, channels provide real-time communication between servers, apps, and devices. You can learn more about channels using this link: https://pusher.com/docs/channels)
    • Get Configuration for Project (Channels/ /App Keys):
    • Create a Project in https://www.mongodb.com/
    • Create a collection in MongoDB.
  • Setup the Server code
    • Create Node project
    • Install Pusher, Mongoose, and express packages (npm install express mongoose pusher)
    • Create an instance of MongoDB Collection so we can push data to the collection.
    • mongoInstance.js
       
      // import mongoose
      const mongoose = require('mongoose'); 
      
      // Create Schema for Collection
      const testSchema = mongoose.Schema({
         message: String,
         name: String,
         timestamp: String,
         received: Boolean,
      }); 
      
      
      // Assign schema to collection
      const dbCollectionRef = mongoose.model('messagescollections', whatsappSchema);  
      
      // Export instance of collection doc
      module.exports = { dbMessagesCollectionRef }; 
           
    • Trigger events from your server : Create Pusher trigger when new document created then it will useful for client server communication:
    • server.js
      // initialize pusher
      const mongoose = require('mongoose');
      const Pusher = require('pusher');
      
      const pusher = new Pusher({
            appId: '107xxxx',
            key: '3fxxxxxxxxxxxxxx',
            secret: '1526xx',
            cluster: 'ap2',
            encrypted: true,
      });
      
      // Connect Mongo db
      // db config
      const connection_url = 'xxxx';
      mongoose.connect(connection_url, {
            useCreateIndex: true,
            useNewUrlParser: true,
            useUnifiedTopology: true,
      });
      
      const db = mongoose.connection;
      
      // Once our connection is opens then our callback is called. let's assume that all following code is within this callback.
      db.once('open', () => {
            const msgCollection = db.collection('messagescollections');
            const changeStream = msgCollection.watch();
            changeStream.on('change', (change) => {
               if (change.operationType === 'insert') {
                  const messageDetails = change.fullDocument;
      
                  /* Created ‘my-event’ event trigger, when new document is added then called this trigger and
                  add data which need to pass on UI for real time */
                  pusher.trigger(‘channel_name', 'my-event', {
                        message: messageDetails.message,
                        name: messageDetails.name,
                        timestamp: messageDetails.timestamp,
                        received: messageDetails.received,
                        _id: messageDetails._id
                  });
               }
            });
      });        
           
    • Setup UI for listen to real-time update and Update UI accordingly
      • Create react project
      • Install Pusher Package (npm install pusher-js)
      • Open a connection to the channel using the key and cluster which we noted down earlier in the first step.
        const pusher = new Pusher(‘api_key’, { cluster: 'ap2' });
        
      • Subscribe to a channel: We publish an event to a channel called my-channel, and a web app will receive this event. But to receive this event, your web app first needs to subscribe to the my-channel channel. Do this with pusher.subscribe:
         const channel = pusher.subscribe('channel_name');
      • Listen for events on your defined channel: Every published event has an "event-name". The event you will publish will have the event name for ex. Here, ‘my-event’. Bind event which is triggered from the server when in new document is created in backed and Pushed data to channel
        channel.bind(‘my-event’, function (newMessage) {
           // new Message 
        });

In this way, you can use pusher with MongoDB. and Listen to real-time updates in react.

contact-us Request a callback WhatsApp