Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access oplog in mongoose.js?

I have app that is using mongoose.js. Till now I was using single instance of mongod. But recently I changed to replica set.

How I can access in mongoose.js the oplog collection? I mean how I can get collection from another db (local)? So let's say I am connected to db and have mongoose.connection - How I can query oplog now?

like image 977
user606521 Avatar asked Jan 12 '23 08:01

user606521


1 Answers

You can access another database in mongoose by using the mongoose.connect method, using a MongoDB URL to specify the database. For example, to connect to to the "local" database where the oplog is found:

mongoose.connect('mongodb://localhost/local')

You say that you are interested in doing this in order to watch for new entries in the oplog, so you will probably want to use a tailable cursor on the "oplog.rs" collection once the connection to the "local" database is established, for example:

mongoose.connection.once('open', function callback () {
    var collection = mongoose.connection.db.collection('oplog.rs')
    collection.find({}, {tailable: true}).each(function(err, entry) {
        if (err) {
            // handle error                                                                                                                                                    
        } else {
            // got a new oplog entry                                                                                                                                           
            console.log('--- entry', entry)
        }
    })
});

Hope this is helpful, let me know if you have further questions.

like image 152
Bruce Lucas Avatar answered Jan 22 '23 03:01

Bruce Lucas