In the previous part of the article series, Build Chat Application On MEA2N Stack – Part One, we built a basic chat application on Node.js platform using Express, Angular 2 and socket.io. In this article, we are going to use MongoDB Atlas for saving our chats and retrieving history whenever user will be requested for it.
Prerequisites
- Go through Build Chat Application On MEA2N Stack – Part One.
- Download and install MongoDB Compass from https://www.mongodb.com/products/compass; it will help us to explore and manipulate MongoDB data.
Setup MongoDB Atlas
MongoDB Atlas is a cloud-hosted MongoDB service. MongoDB team will perform DB management, setup, and configuration, software patching, monitoring, backups and clustering.
To create MongoDB instance in the cloud, go to https://www.mongodb.com/cloud/atlas. Click on ‘Get Started for free’. Provide your information and get started. If you have already signed up, then login to the site.
Here you will see clusters created by you on the dashboard. To create a cluster, click on ‘Build a New Cluster’. It will pop up the details page. We need to provide Cluster name, MongoDB version, Cloud provider region, and Instance Size. For demo purposes, we are going to use free tier.

Provide cluster name of your choice and select M0 instance size which is free. It includes 512 MB of storage. Scroll down and provide the admin username and password, which will be used to connect to MongoDB. Click on "Confirm and Deploy". It will start creating the cluster. It will take time up to 10 minutes for free tier.
After cluster creation, select a cluster and click on ‘Connect’. It will pop up a window where you can provide from which IP Address MongoDB will be accessible. For the demo, I have selected that MongoDB will be accessible from anywhere. Then, click on ‘Connect your Application’.
Implementation – Server side (code updates)
Open ‘Chat-App’ project created in previous article. Open a terminal and install mongoose by executing ‘npm install mongoose --save’ command. Then create ‘chatManager.js’ in ‘Chat-App’ folder. Open it and start writing your code.- const mongoose = require('mongoose');
- mongoose.connect("mongodb://coder2xx:<password>@cluster4-shard-00-00-i2q0s.mongodb.net:27017,cluster4-shard-00-01-i2q0s.mongodb.net:27017,cluster4-shard-00-02-i2q0s.mongodb.net:27017/Akshay?ssl=true&replicaSet=Cluster4-shard-0&authSource=admin");
- const db = mongoose.connection;
- db.on('error', () => {
- console.error('Connection error for MONGODB...');
- });
- db.once('open', () => {
- console.log("Connected to MONGODB successfully...");
- });
- const schema = mongoose.Schema;
- const chatSchema = {
- from: String,
- clientId: String,
- text: String
- };
- const chatModel = mongoose.model('Chat', new schema(chatSchema));
- const save_chat = function (chat) {
- console.log(chat);
- var data = new chatModel({
- from: chat.from,
- clientId: chat.clientId,
- text: chat.text
- });
- data.save(function (err, fluffy) {
- if (err) {
- return console.error(err);
- }
- });
- };
- const get_history = function (callback) {
- chatModel.find(function (err, chats) {
- if (err) return console.error(err);
- console.log(chats);
- return callback(chats);
- });
- };
- module.exports = { saveChat: save_chat, getHistory: get_history };
- const chatsManager = require("./chatsManager.js");
- socket.on("send_message", (message) => {
- console.log(socket.client.id + ":)" + message);
- sockets.emit("new_message", { from: socket.client.id, text: message });
- chatsManager.saveChat({
- from: socket.client.id,
- clientId: socket.client.id,
- text: message
- });
- });
- socket.on("get_history", () => {
- console.log("Chat history request from " + socket.client.id);
- chatsManager.getHistory((chats) => {
- console.log("completed...");
- socket.emit("take_history", chats);
- });
- });
Here we need to update ‘send_message’ event listener for save functionality. We have added call to chatsManager.saveChat() function. Then we have added ‘get_history’ event listener, which will get chat history by calling chatsManager.getHistory() method. It will emit ‘take_history’ event for requested client only. We are ready with server side updates. Now it's time to update client side.
Now open app.component.ts and update the code as mentioned.
- clearChatWindow = () => {
- this.messages = [];
- };
- loadChatHistory = () => {
- this.socket.emit("get_history");
- };
clearChatWindow() and loadChatHistory() functiona are added to component. ‘clearChatWindow()’ will assign empty array to messages property. And loadChatHistory() will emit ‘get_history’ event.
- this.socket.on("take_history", (data) => {
- this.messages = data;
- });
Then, add an event listener for ‘take_history’ event. The response received from the event will be directly assigned to messages property. Response is an array of chats sent from the server.
Now, open app.component.html. And add two buttons, one for clearing chat history and another for requesting chat history. Call clearChatWindow() and loadChatHistory() functions on their clicks respectively.
- <button (click)="clearChatWindow()" class="btn btn-default" title="clear chat window"><i class="fa fa-trash" aria-hidden="true"></i></button>
- <button (click)="loadChatHistory()" class="btn btn-default" title="load chat history"><i class="fa fa-history" aria-hidden="true"></i></button>
We are ready with our code. Let’s build an Angular application by executing ‘ng build’ command. Then run ‘node starter.js’ command to start our application.
Open two browsers and hit ‘http://localhost:9696’ from both the browsers. And start chatting…
You can check chat history is getting added in MongoDB using Compass. Use same connection string.
This is basic chat application implementation on MEA2N stack. In future articles we will discuss about building APIs using NodeJs.

Vikash KumarPosted Sep 18, 2017, 5:14 AM
And is it possible to have a form with api.ai? Any clue?
Vikash KumarPosted Sep 18, 2017, 3:26 AM
Hi, thanks for the nice tutorial. Can we have forms in it? I mean can we have small form inside the messenger with buttons and textfields?