Node.js and MongoDB: Building a Real-Time Chat Application

Node.js and MongoDB are two powerful technologies that are commonly used together to build real-time web applications. In this article, we will explore how to build a real-time chat application using Node.js and MongoDB.

Setting Up MongoDB

First, we need to install MongoDB on our machine. You can download MongoDB from the official website (https://www.mongodb.com/try/download/community) and follow the installation instructions for your operating system.

Once MongoDB is installed, we need to create a database for our chat application. Open up the MongoDB shell by running the following command in your terminal:

mongo

Then, create a new database by running the following command in the MongoDB shell:

perl
use chat

This will create a new database called “chat”.

Creating a Node.js Project

Next, we need to create a new Node.js project. Open up your terminal and navigate to the directory where you want to create your project. Then, run the following command to create a new Node.js project:

csharp
npm init -y

This will create a new package.json file for your project.

Installing Dependencies

We need to install some dependencies for our project. Run the following command to install the required dependencies:

lua
npm install express socket.io mongoose

This will install the Express framework for building web applications, the Socket.IO library for real-time communication, and the Mongoose library for interacting with MongoDB.

Creating a Chat Application

Now, we can start building our chat application. Create a new file called “app.js” in your project directory and add the following code:

javascript
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const mongoose = require("mongoose");

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

mongoose.connect("mongodb://localhost/chat", {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
  console.log("connected to database");
});

const messageSchema = new mongoose.Schema({
  author: String,
  message: String
});
const Message = mongoose.model("Message", messageSchema);

app.use(express.static("public"));

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

io.on("connection", function(socket) {
  console.log("a user connected");

  Message.find({}, function(err, messages) {
    if (err) return console.error(err);
    console.log("sending previous messages");
    socket.emit("previous messages", messages);
  });

  socket.on("chat message", function(msg) {
    console.log("message: " + msg);
    const message = new Message({
      author: msg.author,
      message: msg.message
    });
    message.save(err => {
      if (err) return console.error(err);
      console.log("saved message to database");
    });
    io.emit("chat message", msg);
  });
});

server.listen(3000, function() {
  console.log("listening on *:3000");
});

This code sets up an Express application, creates a Socket.IO server, connects to the MongoDB database we created earlier, creates a Message schema for storing chat messages, and sets up the routes for our application.

The io.on("connection", ...) code block listens for new socket connections and emits the previous chat messages to the new client. It also listens for incoming chat messages and broadcasts them to all connected clients.

We also serve static files (such as the HTML, CSS, and JavaScript files) from a “public” directory using app.use(express.static("public")).

Creating the Front-End

Create a new directory called “public” in your project directory. Inside the “public” directory, create a new file called “index.html” and add the following code:

php
<!doctype html>
<html>
  <head>
    <title>Chat App</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="chat-form">
      <input id="author" type="text" placeholder="Name">
      <input id="message" type="text" placeholder="Message">
      <button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script src="app.js"></script>
  </body>
</html>

This code sets up the basic structure of our chat application, including an unordered list for displaying chat messages and a form for sending new chat messages.

Create a new file called “style.css” in the “public” directory and add the following code:

css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
  padding: 20px;
}

form {
  display: flex;
  margin-top: 20px;
}

form input {
  flex-grow: 1;
  padding: 10px;
  font-size: 16px;
}

form button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin-left: 10px;
  cursor: pointer;
}

This code styles our chat application, including the form for sending new chat messages.

Finally, create a new file called “app.js” in the “public” directory and add the following code:

javascript
const socket = io();

const authorInput = document.getElementById("author");
const messageInput = document.getElementById("message");
const chatForm = document.getElementById("chat-form");
const messagesList = document.getElementById("messages");

socket.on("previous messages", function(messages) {
  messages.forEach(function(message) {
    addMessageToUI(message.author, message.message);
  });
});

chatForm.addEventListener("submit", function(e) {
  e.preventDefault();
  const author = authorInput.value;
  const message = messageInput.value;
  const data = { author, message };
  socket.emit("chat message", data);
  addMessageToUI(author, message);
  messageInput.value = "";
});

function addMessageToUI(author, message) {
  const li = document.createElement("li");
  li.innerHTML = `<strong>${author}:</strong> ${message}`;
  messagesList.appendChild(li);
}

This code sets up a Socket.IO client that listens for previous chat messages and new chat messages. It also adds new chat messages to the UI when they are received.

Running the Application

Now that we have all the code for our chat application, we can run it by running the following command in our terminal:

node app.js

This will start our Node.js server and our chat application will be available at http://localhost:3000.

Conclusion

In this article, we have learned how to build a real-time chat application using Node.js and MongoDB. We used Express to build a web application, Socket.IO for real-time communication, and MongoDB for storing chat messages.

0368826868