NodeJS - MongoDB 触发器 [英] NodeJS - MongoDB triggers
问题描述
我正在尝试使用 DerbyJS、Racer 和 MongoDB 开发日志查看器.日志会由不同的源不断插入到 MongoDB 数据库中,我的日志查看器应该能够自动更新用户界面上的日志表.
I'm trying to develop a Log Viewer using DerbyJS, Racer and MongoDB. The logs will be inserted into the MongoDB database by a different source continuously, and my Log Viewer should be able to update the Logs Table on the user interface automatically.
我想知道是否有一种本地方式来监听 MongoDB 事件,例如:
I was wondering if there is a native way of listening to MongoDB events, like:
- On update
- On delete
这些类似于 Oracle DB 触发器.
These would be similar to, for example, Oracle DB triggers.
推荐答案
您可以使用特殊集合监听 mongodb 中的 insert
、update
等事件以及其他数据事件名为oplog
.您只需要使用 mongod --master
或 mongod --replicaSet
在您的数据库实例上启用复制.
You can listen to events like insert
, update
, and other data events in mongodb using special collection named oplog
. You just need to enable replication on your db instance either using mongod --master
or mongod --replicaSet
.
Oplog 实际上是一个被 mongodb 内部用来实现复制的有上限的集合.如果您使用主/从复制,您将找到名为 oplog.$main
的集合,如果您使用副本集,它将被命名为 oplog.rs
.
Oplog is actually a capped collection which is used by mongodb internally to implement replication. If you are using master/slave replication you will find the collection by the name of oplog.$main
, if you are using replica sets it will be named oplog.rs
.
您可以在 oplog 上使用可尾光标,应该可以.
You can use a tailable cursor on oplog, that should work.
Oplog 实际上就是日志本身.因此,您可能不需要为了记录目的而单独存储它们.但是它的大小是固定的.这意味着当其完整的旧数据被删除时.
Oplog, in effect, is logs itself. So you might not need to store them separately for logging purpose. However its size is fixed. Meaning when its full, older data gets deleted.
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
这篇关于NodeJS - MongoDB 触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!