感谢 Sorhus 的提示,我设法解决了这个问题。他的回答包含心跳,我很想避免。然而,它包含了使用 Meteor 的“bindEnvironment”的技巧。这允许访问集合,否则将无法访问。
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);
}));
}
}