我想在我的 Mongo 数据库的 capped
集合(用作日志表)上创建一种“仪表板”。
这就是我创建集合的方式:
db.createCollection( "messages", { capped: true, size: 100000 } );
我做了一个 collection.find()
,带有选项 tailable:true
、awaitdata:true
和 numberOfRetries:- 1
(无限重试)。
令我困惑的是,我希望 find().each() 循环等待新数据(消息)...相反(几秒钟后)它出错了(No more documents在尾游标中
... :-()
这是我正在使用的代码:
var mongo = require('mongodb');
mongo.MongoClient.connect('mongodb://127.0.0.1/myDb', function (err, db) {
db.collection('messages', function(err, collection) {
if (err) {
return console.error('error in status collection:', err);
}
collection.find( // open tailable cursor
{},
{ tailable: true, awaitdata: true, numberOfRetries: -1 }
).each(function(err, doc) {
if (err) {
if (err.message === 'No more documents in tailed cursor') {
console.log('finished!');
} else {
console.error('error in messages collection:', err);
}
} else {
if (doc) {
console.log('message:', doc.message);
}
}
})
});
});
我错过了什么?
更新:
直到现在还没有收到任何决定性的答案,我推断 MongoDb 可尾集合
还没有准备好迎接黄金时段... :-((
遗憾地放弃了更经典和更强大的 fs 日志记录解决方案......
最佳答案
您可以设置订阅者功能,使用 tailable find()
订阅新的 MongoDB 文档。 光标作为 node.js stream 强>。下面证明了这一点:
// subscriber function
var subscribe = function(){
var args = [].slice.call(arguments);
var next = args.pop();
var filter = args.shift() || {};
if('function' !== typeof next) throw('Callback function not defined');
var mongo = require('mongodb');
mongo.MongoClient.connect('mongodb://127.0.0.1/myDb', function(err, db){
db.collection('messages', function(err, collection) {
var seekCursor = collection.find(filter).sort({$natural: -1}).limit(1);
seekCursor.nextObject(function(err, latest) {
if (latest) {
filter._id = { $gt: latest._id }
}
var cursorOptions = {
tailable: true,
awaitdata: true,
numberOfRetries: -1
};
var stream = collection.find(filter, cursorOptions).sort({$natural: -1}).stream();
stream.on('data', next);
});
});
});
};
// subscribe to new messages
subscribe( function(document) {
console.log(document);
});
来源:How to subscribe for new MongoDB documents in Node.js using tailable cursor
关于javascript - Mongodb:如何在上限集合上创建 `tail -f` View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081812/