Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

CodeProjectMongoDBNode JS
Home›CodeProject›Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io

Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io

By SibeeshVenu
December 4, 2017
975
0
Share:
Socket.io Output

[toc]

Introduction

In this article, we are going to a chat application in Node JS  with the back end MongoDB.  We will also be using Mongoose for creating the MongoDB models and Socket.io for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to 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 on the mentioned technologies. I hope you will like this article.

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 on your application. And with the release of few technologies we can create such application without any hassle. It is much more easier than ever. Here we are also going to create a chat application. A basic knowledge of Node JS, 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.

{
 "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 that 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 as 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 a 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 which uses these controls.

Start developing the chat app

Till now, 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 in 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 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 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 requests in our index.html file which will the post API in our server.js file.

index.html

function postChat(chat) {
        $.post("http://localhost:3020/chats", chat)
}

server.js

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 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.

app.use(bodyParser.json());
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

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.

server.js

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

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 to database
  2. Show the chats in multiple clients, here in our application, if you are opening the URL in multiple browser instance, 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.

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 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 do 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, other wise 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.

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.

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 which is needed? Could you find this post as 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.

Kindest Regards
Sibeesh Venu

TagsChat Application in Node JSChat Application using Socket.ioMongoDBMongooseNode JSSimple client side chat applicationSocket.io
Previous Article

Using MongoDB on Node JS Application Using ...

Next Article

C# Corner MVP 2017

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • node_js_tool_for_visual_studio
    Node JSSQL

    SQL Server CRUD Actions Using Node JS

    November 27, 2016
    By SibeeshVenu
  • MongoDB Data Insertion
    MongoDBNode JS

    Using MongoDB on Node JS Application Using Mongoose

    December 3, 2017
    By SibeeshVenu
  • MongoDB

    Continue With Learning Indexes in MongoDB

    March 7, 2018
    By SibeeshVenu
  • MongoDB

    Learn MongoDB With Me – Part 2

    March 2, 2018
    By SibeeshVenu
  • MongoDB

    Learn MongoDB With Me

    February 22, 2018
    By SibeeshVenu
  • Node JS

    Introduction to Node JS

    June 19, 2015
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version