Meteor应用程序上的警报/通知不会出现

我创建了一个新的“警报”集合。 它显示未读消息的数量。 消息将被提交并显示,并且控制台或服务器上没有其他错误。

第二个问题是,当我点击特定房间时,它应该将所有新消息标记为“已读”。 不知何故,这个数字还有。 错误显示Exception in queued task: .added@http://localhost:3000/app/lib/collections/messages.js中的Exception in queued task: .added@http://localhost:3000/app/lib/collections/messages.js

文件结构:

  • roomList.js – 显示所有房间的列表,显示未读消息的数量
  • roomDetail.js – 当点击列表中的特定房间时,会将消息标记为
    “读”,未读数字消失。
  • alerts.js(提醒集合)
  • messages.js(消息集合)
  • rooms.js(客房collections)

出版物和子书面

 Meteor.publish('alerts', function() { return Alerts.find({ userId: this.userId, read: false }); }); Meteor.subscribe('alerts') 

提醒集合js

 Alerts = new Mongo.Collection('alerts'); Alerts.allow({ update: ownsDocument, //if removed, shows error: // insert failed: Access denied. No allow validators set on restricted collection for method 'insert'. insert: function(){ return true; } }); createMessageAlert = function(message) { if ( message.user !== Meteor.userId() ){ Alerts.insert({ userId : message.user, roomId : Router.current().params._id, //params id of current room messageId : message._id, read : false }); } }; 

roomDetail.js

  Messages.insert({ roomId : Router.current().params._id, msg : message, user : Meteor.user()._id }); template.find('input').value = ''; createMessageAlert(message); 

roomsList.js

 Template.list.helpers({ alerts: function (){ return Alerts.find({ userId: Meteor.userId(), read: false }); }, alertCount: function(){ return Alerts.find({ userId: Meteor.userId(), read: false }).count(); } }); Template.allRooms.events({ 'click a': function() { //click the a href to go into roomDetail Alerts.update(this._id, {$set: {read: true}}); } }); 

终极解决方案

Messages集合中添加新消息时,应从触发器调用createMessageAlert

先决条件:

  1. 为Messages集合创建一个触发器(MSG_OBSERVER),无论何时向集合添加任何内容,都会调用随添加的文档对象提供的createMessageAlert方法,因此您可以在方法内部进行操作并执行所需的操作。
  2. 当您更新警报集合时。 该集合应以这种方式发布(命名为“null”),它应该是被动的,并且应该可以从不同浏览器实例访问同一帐户的所有实例中获得。

履行

只需在collections.js中添加以下代码即可

 Meteor.method( 'createMessageAlert': function(id, fields) { if ( fields.user !== Meteor.userId() ){ Alerts.insert({ userId : fields.user, roomId : Router.current().params._id, //params id of current room messageId : id, read : false }); } } ); var MSG_OBSERVER = Messages.find(); MSG_OBSERVER.observe({ added: function(id, fields){ Meteor.call('createMessageAlert', id, fields); } }); Meteor.publish(null ,function() { // null name means send to all clients //use Messages.insert() to generate a fake message and add data in below params Meteor.call('createMessageAlert', id, fields); return Alerts.find(); }); 

  1. 如果您再次阅读先决条件,您将理解代码。 确保您在客户端订阅了所需的集合。 此代码使每个集合都涉及并触发响应和响应。
  2. 无论您将添加什么消息,也会添加到警报中。
  3. 发布“null”只会将数据发布到所有客户端,使得UI行为更加健壮和异步。(我在显示实时图形时使用此function,您甚至不必刷新UI并反映您的数据。)
  4. 在发布“null”时,您可以创建一个假的Message OBJ并将其添加到调用createMessageAlert函数中。 您必须执行此操作,因为您必须在服务器重新启动时启动发布。 明智地选择消息Obj,这样它不会影响工作流程。