1つのオプションは、最新のユーザー参加メッセージを更新するだけのメソッド呼び出しを行うことです。
function formatJoinMessage(username,count) {...}
if (Meteor.isServer) Meteor.startup(function () {Chats._ensureIndex({modified:-1}); ...});
Meteor.methods({
join:function() {
var joinMessage = Chats.find({type:MESSAGE_TYPE_JOINED,userId:this.userId}).sort({modified:-1}).fetch()[0];
if (joinMessage)
Chats.update({_id:joinMessage._id},{$inc:{joins:1},$set:{text:formatJoinMessage(this.userId,joinMessage.joins+1),modified:new Date()});
else
Chats.insert({user:this.userId,joins:1,modified:new Date(),text:formatJoinMessage(this.userId,1)});
}
)};
サーバードキュメントを変更したくないですか?それは大丈夫ですが、概念的にはチャット参加はチャットメッセージではありません。したがって、ドキュメントmeta
にはこのようなもののフィールドが必ずあるはずです。chat
しかし、あなたがそれをしたくないと仮定します。私はこのようなことをします:
var userIdToName = function(userId) {...}; // some kind of userId to name helper
Template.chatroom.msg = function() {
var messages = Chat.findOne(Session.get("currentChat")).messages; // msg in your code?
return _.reduce(messages,function (newMessages, currentMessage) {
var lastMsg = newMessages[newMessages.length-1];
if (currentMessage.type == MESSAGE_TYPES_JOIN) {
if (lastMsg && lastMsg.type == MESSAGE_TYPES_JOIN && currentMessage.user == lastMsg.user) {
currentMessage.timesJoined = lastMsg.timesJoined+1;
newMessages.shift();
} else {
currentMessage.timesJoined = 1;
}
currentMessage.chatMsg = userIdToName(lastMsg.user) + " joins the chat &mult;" + currentMessage.timesJoined.toString();
}
return newMessages.concat(currentMessage);
},[]);
}
これはちょっとおかしなことです。チャットの現在のメッセージで見つかったすべての参加メッセージを1つのメッセージに「削減」すると言えば十分です。プロパティを動的に追加しますtimesJoined
; ドキュメントには表示されません。ただしtype
、参加メッセージと通常のメッセージの違いを知らせるフィールドが必要です。
少なくともそのメタデータがない場合、チャットアプリケーションはうまく機能しません。モデルを変更することを躊躇しないでください!