Node.js 监听 MongoDB 变化
Node.js 有没有办法监听 MongoDB 集合中特定数据的更改,并在发生更改时触发事件?
Is there a way for Node.js to listen to a change in a particular data in a collection of MongoDB, and fire an event if a change happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嗯,这是一个老问题,但我也在为同样的事情而苦苦挣扎。我发现了一些帮助我整合解决方案的花絮,并将其作为库发布:
https ://github.com/TorchlightSoftware/mongo-watch
该库是用coffeescript编写的。这是一个 javascript 示例,供喜欢的人参考。
Well, this is an old question, but I was struggling with the same thing. I found a number of tidbits that helped me put together a solution, and I've published it as a library:
https://github.com/TorchlightSoftware/mongo-watch
The library is written in coffeescript. Here's an example in javascript, for those that prefer.
MongoDB 显然现在支持触发器和监视,这个答案已经过时了。
[原始]我相信您正在寻找数据库触发器。
不幸的是,MongoDB 还不支持它们,所以我认为你不能直接从数据库监听更改。您需要设置某种通知系统(例如发布/订阅),以便在集合发生更改时向感兴趣的各方发出警报。
MongoDB apparently now supports triggers and watch, this answer is outdated.
[Original] I believe you are looking for a database trigger.
Unfortunately, MongoDB has no support for them yet, so I don't think you can listen for changes directly from the database. You'll need to setup some sort of notification system (e.g. pub/sub) that alerts interested parties when a collection has changed.
MongoDB 3.6引入了变更流,旨在解决这个问题。
这是一个示例: https://github.com/thakkaryash94/mongodb-change-流-nodejs-示例
MongoDB 3.6 introduced change streams, which are designed to solve precisely this problem.
Here's an example: https://github.com/thakkaryash94/mongodb-change-streams-nodejs-example
嗯,有点晚了。
但是,如果有人希望通知 MongoDB 对 node.js 的更改,那么他们可以使用 mubsub 库。
这是一个活跃的库,很容易与 Nodejs 集成。
它使用 Mongo 的可尾游标和上限集合。
它以发布/订阅方式工作,在文档插入 MongoDB 时通知订阅者。
有关详细信息,请查看 Github。
Well, kind of late.
But still, if someone looking to notify the MongoDB changes to the node.js then they can use mubsub library.
This is active library and very easy to integrate with nodejs.
It uses Mongo's tailable cursors and capped collections.
It works in pub/sub fashion to notify the subscriber when the document inserted into the MongoDB.
Check on Github for details.