0

I have created chat application using socket.io and I am storing array of messages. Each array object has message and date. The chat app is working only on client side i.e when I refresh the page all previous chats are gone. How can I store the messages programmatically ? using mongodb, nodejs/express and reactjs on client side ?

Code:

server.js:

const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');

const app = express();

const db = require('./config/keys').mongoURI;

mongoose.connect(db, {useNewUrlParser: true})
  .then(() => console.log('Mongodb connected...'))
  .catch( err => console.log(err));

const port = 5000;

let server = app.listen(5000, function(){
  console.log('server is running on port 5000')
});

let io =  socket(server);

io.on("connection", function(socket){
  console.log("Socket Connection Established with ID :"+ socket.id)

      socket.on('SEND_MESSAGE', data => {
        io.emit('RECEIVE_MESSAGE', data);
      });

})

messageSchema.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const MessageSchema = new Schema({
  message: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Message = mongoose.model('Message', MessageSchema);

chat.js:

import React, { Component } from 'react'
import './chat.css'
import io from "socket.io-client";

export default class Chat extends Component {

    constructor(props){
        super(props);

        this.state = {
            message: '',
            date: '',
            messages: []
        };

        const socket = io('localhost:5000');

        this.sendMessage = event => {
            event.preventDefault();

            if(this.state.message !== ''){
                socket.emit('SEND_MESSAGE', {
                    message: this.state.message,
                    date: Date.now()
                });
                this.setState({ message: '', date: '' });
            }
        };

        socket.on('RECEIVE_MESSAGE', data => {
            addMessage(data);
        });

        const addMessage = data => {
            console.log(data);
            this.setState({
              messages: [...this.state.messages, data],
            });
            console.log(this.state.message);
            console.log(this.state.messages);
        };

    }

    render() {
        return (
        <div>
                <div id="status"></div>
                <div id="chat">
                    <div className="card">
                        <div id="messages" className="card-block">
                            {this.state.messages.map((message, index) => {
                                    return (
                                        <div key={index} className="msgBox"><p className="msgText">{message.message}</p></div>
                                    )
                            })}
                        </div>
                    </div>
                    <div className="row">
                        <div className="column">
                            <input id="inputmsg" type="text" placeholder="Enter Message...."
                            value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
                        </div>
                        <div className="column2">
                            <button id="send" className="button" onClick={this.sendMessage}>Send</button>
                        </div>
                    </div>
                </div>
        </div>
        )
    }
}

Screenshot:

enter image description here

What modifications should I make in server.js and chat.js so that the chat messages get stored in mongodb database. Do I need to create API endpoint for storing and retrieving previous chats ? Note: I have setup mongodb in mlab with database name mongochat and collection name = chat.

1 Answer 1

2

You can try edit your server.js, and do something like this:

var messageSchema = require("path/to/schema");

.
. 
.

socket.on('SEND_MESSAGE', data => {
   io.emit('RECEIVE_MESSAGE', data);
   var newDate = new Date();
   const message = new messageSchema({
       'message': data,
       'date': newDate
   })
   message.save((err, data) => {
      if(err) //do something
      else // do whatever you want
   })
});

You can also create a middleware to provide you a simple service between the MongoDB and the APP.

Sign up to request clarification or add additional context in comments.

2 Comments

I could not get this line -> message.save((err, data) => { message.save is mongodb specific or socket.io ?
It's specific for mongoose, u can do like this to: message.save(function(err,data){ ... })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.