插入到堆栈顶部的 MongoDB 并监听更新
这是我的案例: 我在 Node.Js 中有一个 MongoDB 集合。
假设三个元素:a、b、c 我想插入新元素作为第一个元素,并希望最后一个元素消失。
所以它会是: d, a, b
在下一次迭代中: e、d、a
1.如何进行这种插入?
2.是否有机会监听来自另一个node.js应用程序的那些插入?像这样的东西
collection.on('update', function() {
console.log('updated');
});
Here is my case:
I have a MongoDB collection in Node.Js.
Let's say three elements: a, b, c I want to insert new element as the first one and want the last one to go out.
So it would be:
d, a, b
In next iteration:
e, d, a
1.How to do that kind of insetion?
2.Is there a chance to listen for those insetions from another node.js app? Something like
collection.on('update', function() {
console.log('updated');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上限集合 MongoDB 中的保留插入顺序并丢弃最旧的项目总集合大小(不幸的是以字节为单位测量)。看起来非常适合您的场景。
我相信MongoDB中还没有触发/通知机制,只有手动轮询。
Capped collections in MongoDB preserve insertion order and discard the oldest items based on the total collection size (unfortunately measured in bytes). Seems like ideal fit for your scenario.
I believe there is no trigger/notification mechanism in MongoDB yet, only manual polling.
处理此问题的另一种方法是编写一个自定义队列对象,如果队列中的项目总数超出了您的要求,则当新项目入队时,该对象将使最后一个项目出列,并发出“项目已添加”事件,该事件的其他部分您的应用程序可以监听。
下面是一些通用示例代码,您可以在其中将 Array、length、shift() 和 unshift() 的引用替换为对 MongoDB 的调用:
可用作:
控制台输出:
Another way to handle this would be to write a custom Queue object that would dequeue the last item when a new item was enqueued if the total number of items in the queue exceeded your requirements, and emit an 'item added' event that other parts of your application could listen for.
Here's some generic example code in which you would replace refs to Array, length, shift() and unshift() with calls to MongoDB:
which could be used as:
console output: