Lalitha
Lalitha

Reputation: 401

Auto update changes in mongodb directly on frontend without page refresh with Node Socket.io and angularjs

My question is, incase I manually add one more message inside mongodb directly, how can I make it automatically visible in active UI client pages without a need of refreshing. My code is below. What happens in mine is, when new client is visiting page, existing records in mongo is displayed and thus connection is maintained. But if I add one more record inside mongo directly and load a new client, only that will have the record and others get it only on refresh.

app.js(Server side script)

mongoose.connect("mongodb://localhost:27017/some");
    var mschema=mongoose.Schema({
       message: String,
       time : {type:Date ,default: Date.now}

    });
   io.sockets.on('connection', function (socket) {
    chatmsg.find({},function(err,docs)
    {
        if(err)
            console.log("errorr");
        else
             socket.emit('old msgs',docs);
    })
    socket.on('message', function(message) {
        var newmsg=new chatmsg({message : message});
        newmsg.save(function(err)
        {
            if(err)
            {
                console.log("error");
            }
            else
                io.sockets.emit('new message',message) ;
        })

            })

controller.js (Client side script)

    var socket=io("http://localhost:3200");

$scope.sendemit=function()
{
    console.log("inside function"+$scope.textchat);
    socket.emit('message', $scope.textchat);
    $scope.textchat="";
}

  socket.on('new message', function (message) {
         $("#chat").append(message+"<br/>");
   } );

  socket.on('old msgs',function(docs)
  {
    for(var i=0;i<docs.length;i++)
    {
    console.log(JSON.stringify(docs[i].message));
  $("#chat").append(docs[i].message+"<br/>");
    } 
  })

index.html

   <form >
   <input class="form-control" type="text" ng-model="textchat">
   <button class="btn btn-success" ng-click="sendemit()">Send</button>
  </form>
</div>
<div class="container-fluid">
   <div id="chat"></div>
</div>

Upvotes: 1

Views: 1455

Answers (1)

inaitgaJ
inaitgaJ

Reputation: 1487

You might want to switch database, there is one for this specific use-case.

RethinkDB automatically pushes data changes to apps.

There is a node library called second-thought. It has some utility functions to make database operations easier.

Upvotes: 2

Related Questions