因为 Meteor.users 是一个与任何其他 Meteor 集合一样的集合,所以您实际上可以像任何其他 Meteor 集合一样细化它的公开内容:
Meteor.publish("users", function () {
//this.userId is available to reference the logged in user
//inside publish functions
var _role = Meteor.users.findOne({_id: this.userId}).role;
switch(_role) {
case "counselor":
return Meteor.users.find({}, {fields: { sessionRemaining: 0, counselor: 0 }});
default: //student
return Meteor.users.find({}, {fields: { counselorSpecific: 0 }});
}
});
然后,在您的客户端中:
Meteor.subscribe("users");
因此,Meteor.user()
将根据登录用户的角色自动截断。
这是一个完整的解决方案:
if (Meteor.isServer) {
Meteor.publish("users", function () {
//this.userId is available to reference the logged in user
//inside publish functions
var _role = Meteor.users.findOne({ _id: this.userId }).role;
console.log("userid: " + this.userId);
console.log("getting role: " + _role);
switch (_role) {
case "counselor":
return Meteor.users.find({}, { fields: { sessionRemaining: 0, counselor: 0 } });
default: //student
return Meteor.users.find({}, { fields: { counselorSpecific: 0 } });
}
});
Accounts.onCreateUser(function (options, user) {
//assign the base role
user.role = 'counselor' //change to 'student' for student data
//student specific
user.sessionRemaining = 100;
user.counselor = 'Sam Brown';
//counselor specific
user.counselorSpecific = { studentsServed: 100 };
return user;
});
}
if (Meteor.isClient) {
Meteor.subscribe("users");
Template.userDetails.userDump = function () {
if (Meteor.user()) {
var _val = "USER ROLE IS " + Meteor.user().role + " | counselorSpecific: " + JSON.stringify(Meteor.user().counselorSpecific) + " | sessionRemaining: " + Meteor.user().sessionRemaining + " | counselor: " + Meteor.user().counselor;
return _val;
} else {
return "NOT LOGGED IN";
}
};
}
和 HTML:
<body>
<div style="padding:10px;">
{{loginButtons}}
</div>
{{> home}}
</body>
<template name="home">
<h1>User Details</h1>
{{> userDetails}}
</template>
<template name="userDetails">
DUMP:
{{userDump}}
</template>