Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating a Chat App in Node.js With Express, MongoDB, Mongoose, and Socket.io

DZone's Guide to

Creating a Chat App in Node.js With Express, MongoDB, Mongoose, and Socket.io

With a couple new technologies and with basic knowledge of Node JS, MongoDB, JavaScript, and JQuery, we can create a chat app without any hassle.

· AI Zone ·
Free Resource

Did you know that 50- 80% of your enterprise business processes can be automated with AssistEdge?  Identify processes, deploy bots and scale effortlessly with AssistEdge.

In this article, we are going to create a chat application in Node JS with the backend 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 Node JS, I strongly recommend you read some articles on it 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 have some basic knowledge on the mentioned technologies.

You can always clone or download the source code here!

Background

Creating a chat application is always an interesting thing to do. And it is a good way to learn a lot because you are creating some interactions with your application. With the release of a few technologies, we can create such an application without any hassle. It is easier than ever. Here, we are going to create a chat application. Basic knowledge of Node JS, MongoDB, JavaScript, and JQuery is more than enough to create this project.

Let's 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.

{
 "name": "chatapp",
 "version": "1.0.0",
 "description": "A chat application in Node JS, which uses MongoDB, Mongoose and Socket.io",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1"
 },
 "keywords": [
 "Node",
 "JS",
 "MongoDB",
 "Mongoose",
 "Socket.io"
 ],
 "author": "Sibeesh Venu",
 "license": "ISC",
 "dependencies": {
 }
}

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

npm install --save express
npm install --save mongoose
npm install --save body-parser
npm install --save socket.io

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

"dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongoose": "^4.13.6",
    "socket.io": "^2.0.4"
  }

Creating an App Using Express

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

var express = require("express")
var app = express()
app.listen(3020,()=>{
 console.log("Well done, now I am listening...")
})

I hope you are getting the desired output; if not, please don't worry... just double check the codes you had 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 Cannot GET / — no worries. To fix that, you need to add the following code block to your server.js file:

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.

<!DOCTYPE html>
<title>Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" crossorigin="anonymous"></script>

<div class="container">
    <br>
    <div class="jumbotron">
        <h1 class="dispaly-4">Start Chatting</h1>
        <br>
        <input id="txtName" class="form-control" placeholder="Name" type="text">
        <br>
        <textarea id="txtMessage" class="form-control" placeholder="Message"></textarea>
        <br>
        <button id="send" class="btn btn-success">Send</button>
    </div>
    <div id="messages"></div>
</div>

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

Start Developing the Chat App

Up to now, it was all basic, and we have done it well. Now, it's time to go and write some advanced code! 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.

<script>
    $(() => {
        $("send").click(() => {
            var chatMessage = {
                name: $("#txtName").val(), chat: $("#txtMessage").val()
            }
            postChat(chat)
        })
    })

    function postChat(chat){
        console.log(chat)
    }

</script>

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

Setting Up the Database

We are going to set up our database in mLab, as explained in this article. Let's just require Mongoose and do the needed changes.

var express = require("express")
var mongoose = require("mongoose")

var app = express()

var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"
app.use(express.static(__dirname))

var Chats = mongoose.model("Chats", {
    name: String,
    chat: String
})

mongoose.connect(conString, { useMongoClient: true }, (err) => {
    console.log("Database connection", err)
})

app.listen(3020, () => {
    console.log("Well done, now I am listening...")
})

Creating a Post Request

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

function postChat(chat) {
        $.post("http://localhost:3020/chats", chat)
}
app.post("/chats", async (req, res) => {
    try {
        var chat = new Chats(req.body)
        await chat.save()
        res.sendStatus(200)
    } catch (error) {
        res.sendStatus(500)
        console.error(error)
    }
})

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

You may be getting an error that says:

(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

To fix this, we need to use the default promise instead of the Mongoose promise. Let's change that. Add mongoose.Promise = Promise to our server.js file. Give it a try after setting it.

If it is still not working right and you are getting undefined at the place var chat = new Chats(req.body) in our Post API, 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.

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

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 code 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 on our index.html page, which will call the Get API.

function getChats() {
     $.get("/chats", (chats) => {
         chats.forEach(addChat)
     })
}

function addChat(chatObj){
    $("#messages").append(`<h5>${chatObj.name} </h5><p>${chatObj.chat}</p>`);
}

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

app.get("/chats", (req, res) => {
    Chats.find({}, (error, chats) => {
        res.send(chats)
    })
})

Here, we are passing { } to our find function. This means that 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 sent.

Implementing Socket.io

Now the chat we are sending is getting saved to our database and we are able to load it on page load. Is it the behavior of a perfect chat application? Absolutely not; a perfect chat application would be able to:

  1. Show the chat message to the UI right after the data is inserted into the database.
  2. Show the chats in multiple clients. In our application, if you are opening the URL in multiple browser instances and you need to show chats to both instances, you have to refresh the pages. 

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 have to require the HTTP server first, then set our app. You can see more information on Socket.io here.

var http = require("http").Server(app)
var io= require("socket.io")(http)

Enabling the Connection

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

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

Listen Using the New HTTP Server

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

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

Changes in Script

Let's listen for the event "chat" now in our HTML page.

var socket = io()
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 like:

Uncaught ReferenceError: io is not defined.

Emit the Event

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

app.post("/chats", async (req, res) => {
 try {
 var chat = new Chats(req.body)
 await chat.save()
 res.sendStatus(200)

 //Emit the event
 io.emit("chat", req.body)

 } catch (error) {
 res.sendStatus(500)
 console.error(error)
 }
})

Let's just run our application in two browser instances and check for the 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.

Your Turn. What Do You Think?

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

Consuming AI in byte sized applications is the best way to transform digitally. #BuiltOnAI, EdgeVerve’s business application, provides you with everything you need to plug & play AI into your enterprise.  Learn more.

Topics:
ai ,chat application ,machine learning ,tutorial ,ai app ,node js ,mongodb ,mongoose ,socket.io ,javascript

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}