我知道向用户集合添加数据的经典方法是在profile
数组中,但根据this document,它不是存储数据的最佳方式。
是否有替代方法,例如在同一级别的用户集合的根目录中使用默认字段(_id
,username
等)创建字段?
答案 0 :(得分:0)
您可以通过accountsServer.onCreateUser(func)
功能向用户文档添加额外字段。
例如:
if (Meteor.isServer) {
Accounts.onCreateUser(function(options, user) {
_.extend(user, {
myValue: "value",
myArray: [],
myObject: {
key: "value"
}
});
});
}
请注意:默认情况下,以下Meteor.users
字段会发布到客户username
,emails
和profile
。因此,您需要发布任何其他字段。
例如:
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");
}
答案 1 :(得分:0)
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的回答中所述。