如何向用户文档(不在个人资料中)添加其他字段?

How to add additional fields to user documents (not in profile)?

我知道将数据添加到用户集合的经典方式是在 profile 数组中,但根据 this document,这不是存储数据的最佳方式。

是否有其他替代方法,例如在用户集合的根目录中创建一个与默认字段(_idusername 等)处于同一级别的字段?

您可以通过 accountsServer.onCreateUser(func) 函数向用户文档添加额外的字段。

例如:

if (Meteor.isServer) {
    Accounts.onCreateUser(function(options, user) {
        _.extend(user, {
            myValue: "value",
            myArray: [],
            myObject: {
                key: "value"
            }
        });
    });
}

请注意: 默认情况下,以下 Meteor.users 字段会发布到客户端 usernameemailsprofile.因此,您需要发布任何其他字段。

例如:

if (Meteor.isServer) {
    Meteor.publish("user", function() {
        if (this.userId) return Meteor.users.find({
            _id: this.userId
        }, {
            fields: {
                'myValue': 1,
                'myArray': 1,
                'myObject': 1
            }
        });
        else this.ready();
    });
}

if (Meteor.isClient) {
    Meteor.subscribe("user");
}

profile 字段本身没有任何问题,除了用户可以(当前)默认直接更新他们自己的个人资料。

我不希望这种行为,因为用户可以在配置文件中存储任意数据。

如果开发人员使用该字段作为权限来源,这可能会成为真正的安全风险;例如,将用户的组或角色存储在其中。

在这种情况下,用户可以设置自己的权限和角色。

这是由this code造成的:

users.allow({
  // clients can modify the profile field of their own document, and
  // nothing else.
  update: function (userId, user, fields, modifier) {
    // make sure it is our record
    if (user._id !== userId)
      return false;

    // user can only modify the 'profile' field. sets to multiple
    // sub-keys (eg profile.foo and profile.bar) are merged into entry
    // in the fields list.
    if (fields.length !== 1 || fields[0] !== 'profile')
      return false;

    return true;
  }
});

首先要做的是限制写入:

Meteor.users.deny({
  update() {
    return true;
  }
});

然后可以使用方法和其他授权代码对其进行更新。

如果您添加自己的字段并希望将它们发布给当前登录的用户,您可以使用自动发布来实现:

Meteor.publish(null, function () {
  if (this.userId) {
    return Meteor.users.find({
      _id: this.userId
    }, {
      fields: {
        yourCustomField1: 1,
        yourCustomField2: 1
      }
    });
  } else {
    return this.ready();
  }
});

Meteor.users 只是一个普通的 Mongo.Collection,所以修改它就像任何其他 Collection 一样。还有创建挂钩 Accounts.onCreateUser,它允许您在首次创建用户对象时向其添加自定义数据,如@MatthiasEckhart 的回答中所述。