我创建了一个新的"警告"采集。它显示未读消息的数量。消息被提交并显示,并且控制台或服务器上没有其他错误。
第二个问题是,当我点击特定房间时,它应该将所有新消息标记为"阅读"。不知怎的,这个数字还有。错误显示Exception in queued task: .added@http://localhost:3000/app/lib/collections/messages.js
文件结构:
出版物和子js
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}});
}
});
答案 0 :(得分:1)
终极解决方案:
在消息集合中添加新消息时,应从触发器调用 createMessageAlert 。
<强>先决条件:强>
<强>实施强>
只需在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();
});
<强>释强>