我在向 Meteor 用户对象 (Meteor.user
) 添加自定义用户字段时遇到问题。我希望用户有一个“状态”字段,并且我不想将它嵌套在“配置文件”(即 profile.status)下,我知道默认情况下它是 r/w。 (我已经删除了 autopublish
。)
我已经能够通过
将字段很好地发布给客户Meteor.publish("directory", function () {
return Meteor.users.find({}, {fields: {username: 1, status: 1}});
});
...但我无法获得允许登录用户更新其自己的状态
的设置权限。
如果我这样做
Meteor.users.allow({
update: function (userId) {
return true;
}});
在 Models.js 中,
用户可以为每个 用户编辑所有字段。那可不酷。
我试过做一些变体,比如
Meteor.users.allow({
update: function (userId) {
return userId === Meteor.userId();
}});
和
Meteor.users.allow({
update: function (userId) {
return userId === this.userId();
}});
他们只是让我在控制台中出现拒绝访问错误。
documentation addresses这有点,但没有深入到足够的细节。我犯了什么愚蠢的错误?
(这类似于 this SO 问题,但该问题仅解决如何发布字段,而不是如何更新它们。)
最佳答案
这就是我让它工作的方式。
在服务器中我发布用户数据
Meteor.publish("userData", function () {
return Meteor.users.find(
{_id: this.userId},
{fields: {'foo': 1, 'bar': 1}}
);
});
并设置允许如下
Meteor.users.allow({
update: function (userId, user, fields, modifier) {
// can only change your own documents
if(user._id === userId)
{
Meteor.users.update({_id: userId}, modifier);
return true;
}
else return false;
}
});
在客户端代码中,我更新用户记录的某个地方,只有当有用户时
if(Meteor.userId())
{
Meteor.users.update({_id: Meteor.userId()},{$set:{foo: 'something', bar: 'other'}});
}
关于javascript - 将自定义字段添加到 Meteor 用户时出现权限问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16600827/