Search code examples
node.jsmongodbsocket.ioreal-time-updates

How to listen to changes in a document of some collection in mongodb


I am using socket.io for Real-time communication between server and client so , i wanted to listen to changes in the specific document to update the online list to the client
Here is my Schema for the collection:

var registerCompanySchema = new Schema({
              sn : { type: Number, unique:true }
              , companyName: String
              , employees:[String],
               companyId:{type:Number,unique:true},
               onlineEmployees:[String]  //uname
          });


I am using a array 'onlineEmployees' to store the username of employees who are currently online
I am new to mongoDB....Please provide some details with your answer.


Solution

  • Watching the oplog is probably your best bet, as mentioned in this question.

    If you're using mongoskin you can try a variant on this example from their wiki:

    skin = require "mongoskin"
    db = skin.db "localhost:27017/local"
    
    #Cursor on oplog (a capped collection) which maintains a history for replication
    #oplog can be used only when replication is enabled
    # Use oplog.rs instead of oplog.$main if you are using replica set
    
    oplog = db.collection "oplog.$main"
    cursor = oplog.find({'ns': "icanvc.projects"},{tailable: yes, awaitData: yes})
    
    #Using cursor.nextObject will be slow
    cursor.each (err, log)->
        console.error err if err
        console.log log if not err