javascript - 将自定义字段添加到 Meteor 用户时出现权限问题

标签 javascript meteor

我在向 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/

相关文章:

javascript - 使用 Javascript 显示和隐藏消息

javascript - 实例化对象内的数组为何返回未定义?

javascript - 如何使用 "Select All"复选框传递所有对象?

javascript - 无法使用 JQuery 表单插件进行简单验证来提交表单

Meteor template.rendered - 为什么集合是空的?

mongodb - cursor.observe 如何工作以及如何避免运行多个实例?

javascript - 使用括号,两个 <scripts> 不能在 html 文件中一起工作?

reactjs - node_modules/@types/react-dom/.... 错误。后续变量声明必须具有相同的类型。变量 'a'

Meteor 在 Windows 8.1 上不被识别为内部或外部命令、可运行的程序或批处理文件

javascript - 站点地图的日期格式