Giter Site home page Giter Site logo

mongo-watch's Introduction

Mongo Watch

This watcher ties into the MongoDB replication log (local.oplog.rs) by default, but you can also tie into local.oplog.$main on a master DB. It then notifies your watchers any time the data changes.

** Deprecated **

I'm no longer actively using this library and make no guarantees of a quick response. I'll leave it in its present state, and make some efforts to merge pull requests. If you're interested in maintaining it, please contact me: info at torchlightsoftware.com.

In leiu of this library, I would recommend checking out Meteor, Firebase, or Strongloop/Loopback. All of these have built robust server <-> client replication protocols, and have the resources to maintain and support their solutions.

Overview

In order to use this you must:

replication log

  1. Have access to the oplog. This will not be available on shared DB hosting, as it would reveal everyone else's database transactions to you.
  2. Have replication enabled. This can be done by starting mongod with the option --replSet someArbitraryName. You must then call rs.initiate() from the mongo CLI.

master log

  1. Have access to the oplog. This will not be available on shared DB hosting, as it would reveal everyone else's database transactions to you.
  2. Start your mongod as --master.
  3. Use: new MongoWatch({useMasterOplog:true})

The watcher is fairly low latency and overhead. On my machine a test with a single insert and watcher takes 20ms. The cursor used to tail the oplog is being initialized with {awaitdata: true} so the data should be getting pushed from MongoDB's internal mechanism, instead of polling.

Because the watcher ties in to the oplog, this solution should scale with you as you add more MongoDB nodes, and allow any corresponding application instances to be notified of the same state changes. I have not yet set up a cluster to test this, so I would welcome any comments or feedback you might have.

Happy event driven programming! 8-)

Note: The query functionality previously supported in 0.1.12 is now deprecated. This code will be moved to Particle. Sorry for any inconvenience, but I determined this would be a much cleaner place to separate the APIs and respective responsibilities of the libraries.

Install

npm install mongo-watch

Usage

Watching a collection is as easy as:

MongoWatch = require 'mongo-watch'

watcher = new MongoWatch {format: 'pretty'}

# watch the collection
watcher.watch 'test.users', (event) ->

  # parse the results
  console.log 'something changed:', event

Now when you run an insert you should see the event get logged by the code above.

# create db client for a test transaction
{Server, Db} = require 'mongodb'
client = new Db 'test', new Server('localhost', 27017), {w: 1}
client.open ->
  client.collection 'users', (err, users) ->

    # fire off an update that will trigger the watcher
    users.insert {email: '[email protected]'}, ->

Options

See the applyDefaults function in lib/main.coffee for a list of options and their defaults.

See the tests for more examples.

Authentication

Pass the "username" and "password" options.

watcher = new MongoWatch {username: 'bobross', password: 'happytrees'}

Replica sets

If you pass a replicaSet array it will be used to establish a connection. It should keep working in case the primary changes - i.e. when it dies, and secondary takes it place.

watcher = new MongoWatch {
    replicaSet: [
        {host: "currentPrimary.mongoexample.com", port : 10453},
        {host: "currentSecondary.mongoexample.com", port : 10452}
    ]
}

Debugging

If you pass the onDebug option with a function of your choice, it will be notified of major events in the listener lifecycle. This is useful for troubleshooting if you're not receiving the notifications you expect.

watcher = new MongoWatch {onDebug: console.log}

For reference, here is output taken from the test 'Mongo Watch - insert should emit an event'. You should expect an output similar to this, and if it's breaking down you should be able to see why from the last event that was fired. Are you listening to the right collection?

Ready: false
Emiting 'connected'. Stream exists: true
Adding emitter for: { collection: 'test.users' }
Adding listener on: { collection: 'test.users' }
Data changed: { data:
   { ts: { _bsontype: 'Timestamp', low_: 1, high_: 1362553757 },
     h: { _bsontype: 'Long', low_: -1091839621, high_: 386723518 },
     op: 'i',
     ns: 'test.users',
     o: { email: '[email protected]', _id: 5136eb9d19bd55597e000001 } },
  watching: 'test.users',
  relevant: true }
Emitting event: { channel: 'change:test.users',
  event:
   { ts: { _bsontype: 'Timestamp', low_: 1, high_: 1362553757 },
     h: { _bsontype: 'Long', low_: -1091839621, high_: 386723518 },
     op: 'i',
     ns: 'test.users',
     o: { email: '[email protected]', _id: 5136eb9d19bd55597e000001 } } }
Removing listeners for: test.users

Credits

Kristina Chodorow was very helpful both in documenting the oplog in her blog posts, and in answering some of my questions. Christian Kvalheim's code served as the basis for the cursor connection.

Contributing

Pull requests welcome! Please create a feature branch instead of submitting directly to master. This will help me test/verify before merging.

LICENSE

(MIT License)

Copyright (c) 2013 Torchlight Software [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mongo-watch's People

Contributors

afharo avatar bitmage avatar lgandecki avatar richthegeek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongo-watch's Issues

Mongo selects

Could you please explain how to use mongo selectors? I tried this:

now = new Date()
watcher.query {collName: 'archive', select: { ts: { $gt: now } } }, (err, query) ->

So that mongo-watcher wouldn't tail changes which happened in the past, but I got this:

MongoError: Unsupported projection option: $gt

Thanks in advance for your insight!

Unable to require('mongo-watch')

Hey,

I've been trying to use this module for a couple weeks to watch the oplog of a Mongo DB. However, yesterday, I noticed the following error..

module.js:340
    throw err;
          ^
Error: Cannot find module './lib/main'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/root/git/[REDACTED]/node_modules/mongo-watch/index.js:2:18)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/root/git/[REDACTED]/app/routes/socket-watcher.js:26:19)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at /root/git/[REDACTED]/server.js:70:38
  at Array.forEach (native)
  at walk_routes (/root/git/[REDACTED]/server.js:64:26)
  at Object.<anonymous> (/root/git/[REDACTED]/server.js:78:1)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Function.Module.runMain (module.js:497:10)
  at startup (node.js:119:16)
  at node.js:902:3

The line that is failing on is as follows

var mongo_watch = require('mongo-watch');

So, clearly, Node isn't able to find lib/main - even though it's clearly right there, in lib/main.coffee.

Any ideas on this?

Connecting to replica sets?

Hey there!

Is there any way to connect to replica sets with mongo-watch?
Right now it feels like I'm forced to point the MongoWatch to one specific db, but my guess is that when that server goes down then my app will stop working, even though the replica set carries on with new master.

It'd be nice to be able to provide a mongourl as a configuration, or at least an array of hosts/ports.

Thanks!

client.open() failure due to wrong package dependencies.

Right now dependence "mongodb" used as "*". And because of this when mongodb was release v3.x with breaking API changes, this programm going not work. And we have next eror:

TypeError: client.open is not a function
    at module.exports (path-to-project/node_modules/mongo-watch/lib/connect.coffee:22:10)
    at module.exports (path-to-project/node_modules/mongo-watch/lib/getOplogStream.coffee:5:3)
    at new MongoWatch (path-to-project/node_modules/mongo-watch/lib/main.coffee:34:5)
    at Object.<anonymous> (path-to-project/lib/db.js:408:21)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (path-to-project/api-server.js:17:10)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:383:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:496:3

Where/how do you set username/password if using authentication?

I found a place in lib/main.coffee to set my database, host and port but I cannot figure out where to set the username and password.

I'm getting the following error since I am using authentication:
events.js:72
throw er; // Unhandled 'error' event
^
MongoError: not authorized for query on local.oplog.rs

Thanks!

Lodash dependency in package.json

By default lodash is only a dependency in DevDependencies but it, appears to be, a requirement for production as well.

With just your simple example on github / npm I get unmet dependencies for lodash until such time as I install it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.