Creating A Chat Application In Node.js With Express, MongoDB, Mongoose And Socket.io

Table of contents

  • Introduction
  • Source Code
  • Background
  • Setting up Node application
    • Creating an App using Express
    • Running our application on browser
    • Creating Index page
  • Start developing the chat app
    • Create model from page data
    • Setting up database
    • Creating a Post request
    • Creating a Get request for all the chat data
  • Implementing Socket.io
    • Require the package
    • Enabling the connection
    • Listen using new HTTP Server
    • Changes in script
    • Emits the event
  • Conclusion
  • Your turn. What do you think?

Introduction

In this article, we are going to create a chat application in NodeJS with the back-end MongoDB. We will also be using Mongoose for creating the MongoDB models and Socket.io for making multidirectional chats on multiple client windows. If you are really new to the NodeJS, I strongly recommend you read some articles on the same here. You can also see how you can create a sample Node application with MongoDB and Mongoose here. At the end of this article, I guarantee that you will be having some basic knowledge of the mentioned technologies. I hope you will like this article.

You can always see this article on my blog here

Source Code

You can always clone or download the source code here.

Background

Creating a chat application is always an interesting this to do. And it is a good way to learn a lot because you are creating some interactions with your application. And with the release of a few technologies, we can create such application without any hassle. It is much easier than ever. Here, we are also going to create a chat application. A basic knowledge of NodeJS, MongoDB, JavaScript, jQuery is more than enough to create this project. So, please be with me. Let’s just skip the talking and start developing.

Setting up Node application

This step requires some basic knowledge, please see some of that here. So, as mentioned in that article, we have successfully created our Package.json file and installed the required packages. Let’s review our package.json file.

  1. {  
  2.     "name""chatapp",  
  3.     "version""1.0.0",  
  4.     "description""A chat application in Node JS, which uses MongoDB, Mongoose and Socket.io",  
  5.     "main""index.js",  
  6.     "scripts": {  
  7.         "test""echo \"Error: no test specified\" && exit 1"  
  8.     },  
  9.     "keywords": ["Node""JS""MongoDB""Mongoose""Socket.io"],  
  10.     "author""Sibeesh Venu",  
  11.     "license""ISC",  
  12.     "dependencies": {}  
  13. }  

Let’s install the packages now by running the below commands.

  1. npm install --save express
  2. npm install --save mongoose
  3. npm install --save body-parser
  4. npm install --save socket.io

Now, we have all the dependencies added to the package.json file.

  1. "dependencies": {  
  2.     "body-parser""^1.18.2",  
  3.     "express""^4.16.2",  
  4.     "mongoose""^4.13.6",  
  5.     "socket.io""^2.0.4"  

Creating an App using Express

Let’s create a file named server.js and build an app using Express.

  1. varexpress = require("express")  
  2. varapp = express()  
  3. app.listen(3020, () => {  
  4.     console.log("Well done, now I am listening...")  
  5. })  

I hope you are getting the desired output; if not, please don’t worry, just double check the codes you have written.

Running our application on browser

Let’s run our application on port 3020 and see what we are getting http://localhost:3020/..

Yes, you will get an error as Cannot GET /. No worries! To fix that, you need to add the following code block to your server.js file.

  1. app.use(express.static(__dirname))  

Creating Index page

Here, I am going to create aN HTML 5 page with JQuery and Bootstrap referenced in it.

  1. <!DOCTYPE html>  
  2. <title>Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io</title>  
  3. <linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous">  
  4.     <scriptsrc="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous">  
  5.         </script>  
  6.         <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" crossorigin="anonymous">  
  7.             </script>  
  8.             <scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" crossorigin="anonymous">  
  9.                 </script>  
  10.                 <divclass="container"> <br>  
  11.                     <divclass="jumbotron">  
  12.                         <h1class="dispaly-4">Start Chatting</h1> <br>  
  13.                             <inputid="txtName" class="form-control" placeholder="Name" type="text"> <br>  
  14.                                 <textareaid="txtMessage" class="form-control" placeholder="Message">  
  15.                           </textarea> <br>  
  16.                  <buttonid="send" class="btn btn-success">Send</button>  
  17.             </div>  
  18.         <divid="messages">  
  19.    </div>  
  20. </div>  

As you can see, the page has two text boxes and one button. We will be creating some scripts very soon which uses these controls.

Start developing the chat app

So far, it was all basic, and we have done it well. Now, it is time to go and write some advanced codes. So, are you ready?

Create model from page data

Here, we are going to create the model from the page data, that is, from the controls we have on our page. We will be using JQuery to do so.

  1. <script>  
  2.     $(() => {  
  3.         $("send").click(() => {  
  4.             varchatMessage = {  
  5.                 name: $("#txtName").val(),  
  6.                 chat: $("#txtMessage").val()  
  7.             }  
  8.             postChat(chat)  
  9.         })  
  10.     })  
  11.     functionpostChat(chat) {  
  12.         console.log(chat)  
  13.     }  
  14. </script>  

Now, that we have got the model from the user, let’s save it to the DB.

Model values on browser console
Model values on browser console

Setting up database

We are going to set up our database in mLab as mentioned in this article Using MongoDB on Node JS Application Using Mongoose. So, let’s just use Mongoose and do the needed changes.

  1. varexpress = require("express")  
  2. varmongoose = require("mongoose")  
  3. varapp = express()  
  4. varconString = "mongodb://admin:[email protected]:38319/mylearning"  
  5. app.use(express.static(__dirname))  
  6. varChats = mongoose.model("Chats", {  
  7.     name: String,  
  8.     chat: String  
  9. })  
  10. mongoose.connect(conString, {  
  11.     useMongoClient: true  
  12. }, (err) => {  
  13.     console.log("Database connection", err)  
  14. })  
  15. app.listen(3020, () => {  
  16.     console.log("Well done, now I am listening...")  
  17. })  

Creating a Post request

Now, let’s create a post request in our index.html file which will post the API in our server.js file.

index.html

  1. functionpostChat(chat) {  
  2.     $.post("http://localhost:3020/chats", chat)  
  3. }  

 server.js

  1. app.post("/chats", async (req, res) => {  
  2.     try {  
  3.         varchat = new Chats(req.body)  
  4.         await chat.save()  
  5.         res.sendStatus(200)  
  6.     } catch (error) {  
  7.         res.sendStatus(500)  
  8.         console.error(error)  
  9.     }  
  10. })  

Let’s just run our application and test it out.

You may be getting an error as “(node:10824) DeprecationWarning: Mongoose: mpromise (mongoose’s default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html””, here to fix this, we need to use the default promise instead of the Mongoose promise. Let’s change that. Add this code mongoose.Promise = Promise to our server.js file. Give it a try after setting it.

Still, it is not working right, you are getting undefined at the place, var chat = new Chats(req.body) in our Post API. At this stage, we will have to use our body-parser packages, do you remember the package we have installed? Let’s just require that package var bodyParser = require("body-parser") add the preceding codes to our server.js file.

  1. app.use(bodyParser.json());  
  2. app.use(bodyParser.urlencoded({extended: false }))  

Now, this will convert the request to a JSON object by default. Give it a try again, I am sure you will get the actual value instead of undefined.

Creating a Get request for all the chat data

We have written codes to write our data into our database. We will have to show this data on our page, right? Here, we are going to write the get requests in out index.html page which will call the get API.

index.html

  1. function getChats() {  
  2.     $.get("/chats", (chats) => {  
  3.         forEach(addChat)  
  4.     })  
  5. }  
  6.   
  7. function addChat(chatObj) {  
  8.     $("#messages").append(`<h5>${name}</h5><p>${chatObj.chat}</p>`);  
  9.  

 And call the function getChats() in document ready event.

server.js

  1. app.get("/chats", (req, res) => {  
  2.     Chats.find({}, (error, chats) => {  
  3.         res.send(chats)  
  4.     })  
  5. })  

Here, we are passing {} to our find function, this means, we are going to get all the chats without any filter. Just run your application now, and check whether you are getting the chat messages you had sent.

Retrieving data from a MongoDB
Retrieving data from a MongoDB

Implementing Socket.io

Now, the chat we are sending is getting saved to our database and we are able to load the same on page load. Is it the behavior of a perfect chat application? Absolutely no, a perfect chat application will be able to,

  1. Show the chat message to the UI right after the data gets inserted into the database
  2. Show the chats in multiple clients, here in our application, if you are opening the URL in multiple browser instances, and if you need to show the chats to both instances, you will have to refresh the pages right? This is not a recommended way

That’s why we are going to implement Socket.io in our application.

Require the package

Unlike the other packages, adding socket.io to the application is a different process, we will have to require the HTTP server first, then, set our app. You can see more information on socket.io here.

  1. varhttp = require("http").Server(app)  
  2. vario= require("socket.io")(http)  

Enabling the connection

To enable the connection, we need to use the function io.on.

  1. io.on("connection", (socket) => {  
  2.     console.log("Socket is connected...")  
  3. })  

Listen using new HTTP server

Now, that we have a new HTTP server, and we should change our listen code to our new HTTP.

  1. varserver = http.listen(3020, () => {  
  2.     console.log("Well done, now I am listening on ", server.address().port)  
  3. })  

Changes in script

Let’s do listen to the event “chat” now in our HTML page.

  1. varsocket = io()
  2. socket.on("chat",addChat)

Please do not forget to include the socket.io.js reference in our index page, otherwise you may get an error as “Uncaught ReferenceError: io is not defined”

Emits the event

Once the above step is completed we need to make sure we are emitting the new event on our Post API.

  1. app.post("/chats", async (req, res) => {  
  2.     try {  
  3.         varchat = new Chats(req.body)  
  4.         await chat.save()  
  5.         res.sendStatus(200)  
  6.         //Emit the event  
  7.         io.emit("chat", req.body)  
  8.     } catch (error) {  
  9.         res.sendStatus(500)  
  10.         console.error(error)  
  11.     }  
  12. })  
Let’s just run our application in two browser instances and check for the output.

Socket.io Output
Socket.io Output

Please make sure that you are getting the chats in the second instance when you send it from the first instance of the browser and vice versa.

Conclusion

Thanks a lot for reading. Did I miss anything that you may think is needed? Did you find this post useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Up Next
    Ebook Download
    View all
    Learn
    View all