如何将其他字段添加到用户文档(不在配置文件中)

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

本文关键字:配置文件 用户文档 其他 字段 添加      更新时间:2023-09-26

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

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

profile字段本身没有错,只是用户可以(当前)默认直接更新自己的配置文件。

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

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

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

这是由以下代码引起的:

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的回答中所提到的。

您可以通过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");
}