如何将其他字段添加到用户文档(不在配置文件中)
How to add additional fields to user documents (not in profile)?
我知道向用户集合添加数据的经典方式是在profile
数组中,但根据本文,这不是存储数据的最佳方式。
是否有其他选择,例如在用户集合的根目录中创建一个与默认字段(_id
、username
等)处于同一级别的字段?
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
字段发布到客户端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");
}
相关文章:
- 将当前用户的 ID 推送到 meteorjs 中集合/文档的内部数组
- 如何从多个不同的html页面获得mongodb文档的用户输入
- SoundCloud API-基于系统中的ID创建用户配置文件
- 将jQuery.js文件附加到html文档中
- 在HTML文档中使用XML文件中的数据
- 使用 PHP 将 css/js 文件分配给 html 文档
- 将变量从服务器上的外部文件加载到 HTML 文档中
- 通过oauth令牌passport.js访问用户配置文件
- mongodb用户配置文件添加输入时出现问题
- 如何使用ian:accounts-ui-botstrap-3根据Meteor中的用户输入设置配置文件字段值
- 带有所有用户操作的业务逻辑的Javascript配置文件
- 如何使用Chrome文档中的文件而不是URL
- 如何在angular js中从github获取原始自述文件后将其转换为html格式的文档
- 流星:如何获取用户帐户包以将新的用户文档写入远程集合
- 添加当前用户配置文件metro.js的文档
- 流星自动将地理位置保存到用户文档中
- 如何将其他字段添加到用户文档(不在配置文件中)
- 如何管理用户文档权限设置使用谷歌驱动器Api?(Javascript)
- Meteor.js,Mongo:可以向用户插入新的文档或参数.来自客户端的配置文件
- 访问使用社会注册创建的用户文档