【发布时间】:2014-07-16 09:30:22
【问题描述】:
我正在使用 mongodb 和 nodejs 处理推送通知。 我可以在浏览器中看到新添加的通知(在 Mongodb 中添加) 但是,如果我更新了记录,浏览器中的值不会更新
// if no error get reference to colelction named: 'notifications'
db.collection('notifications', function(err, collection){
if(err) {
throw err;
}
// if no error apply a find() and get reference to doc
collection.find().sort({
$natural: -1
}).limit(1).nextObject(function(err, doc) {
// Rewind the cursor, resetting it to point to the start of the query
if(err) {
throw err;
}
// using tailable cursor get reference to our very first doc
var query = {
_id: {
$gt: doc._id
}
};
var options = {
tailable: true,
awaitdata: true,
numberOfRetries: -1
};
var cursor = collection.find(query, options).sort({
$natural: 1
});
// This function will take cursor to next doc from current as soon as 'notifications' database is updated
function next() {
cursor.nextObject(function(err, message) {
if (err) throw err;
console.log(message.message);
mdsok.volatile.emit('notification', message);
next();
});
}
// what you need to do is: call it first time
next();
});
这就是我在代码中所做的。
当我在 db 中更新相同的值时,我应该如何更新浏览器中的值。
请帮帮我。提前致谢!
【问题讨论】:
-
这是一个可尾游标实现,必须是一个有上限的集合。你真的不应该更新一个有上限的集合。一方面,因为它被“封顶”,所以文档可能不存在。第二,不允许“增长”一个有上限的集合文档。它们旨在充当“队列”,因此“仅插入”。
-
我的实际要求是,我在浏览器中显示一些从 Mongodb 数据库中获取的值。如果该值在 db 中更改,则无需刷新我的页面,我需要使用套接字在浏览器上显示更新的值。谁能给我一个很好的例子来满足这种要求。
-
@NeilLunn,你说的完全正确!我们无法更新上限集合。离开关于上限的集合。现在,我没有使用上限集合。我正在使用普通集合,并且在集合中插入了一些值。现在,每当我更新数据库中的对象时,我都需要触发更新的对象。