由於Sorhus'末端,我設法解決這個問題。他的回答包含了一個我很想避免的心跳。但是,它包含了使用流星的「綁定環境」的技巧。這允許訪問集合,否則該集合將不可訪問。
Meteor.publish("whatever", function() {
userId = this.userId;
if(userId) Stats.update({}, {$addToSet: {users: userId}});
else Stats.update({}, {$inc: {users_anon: 1}});
// This is required, because otherwise each time the publish function is called,
// the events re-bind and the counts will start becoming ridiculous as the functions
// are called multiple times!
if(this.session.socket._events.data.length === 1) {
this.session.socket.on("data", Meteor.bindEnvironment(function(data) {
var method = JSON.parse(data).method;
// If a user is logging in, dec anon. Don't need to add user to set,
// because when a user logs in, they are re-subscribed to the collection,
// so the publish function will be called again.
// Similarly, if they logout, they re-subscribe, and so the anon count
// will be handled when the publish function is called again - need only
// to take out the user ID from the users array.
if(method === 'login')
Stats.update({}, {$inc: {users_anon: -1}});
// If a user is logging out, remove from set
else if(method === 'logout')
Stats.update({}, {$pull: {users: userId}});
}, function(e) {
console.log(e);
}));
this.session.socket.on("close", Meteor.bindEnvironment(function() {
if(userId === null || userId === undefined)
Stats.update({}, {$inc: {users_anon: -1}});
else
Stats.update({}, {$pull: {users: userId}});
}, function(e) {
console.log("close error", e);
}));
}
}
不能感謝你足夠:) – Pawan
雖然這是非常酷,但文檔明確表示它不跟蹤匿名用戶,所以它不能真正回答原來的問題。 – cazgp
@cazgp由於我寫了這篇文章,我已經更新了軟件包來跟蹤匿名用戶。很明顯,我們無法跟蹤'Meteor.users'中的匿名用戶,但他們的連接都被跟蹤。 –