简体   繁体   English

解析:使用云代码将用户添加到角色

[英]Parse: Add user to role using cloud code

Im using parse as a backend for the very first time. 我第一次使用解析作为后端。 In my business the user has to choose between 2 roles at the register page: "Role1" and "Role2". 在我的业务中,用户必须在注册页面上的两个角色之间进行选择:“ Role1”和“ Role2”。 If I understand the docs the access to "_Role" class should be read only, so the best way to add a user to a role while this user is trying to register is through cloud code. 如果我了解文档,则对“ _Role”类的访问应该是只读的,因此在此用户尝试注册时将用户添加到角色的最佳方法是通过云代码。

My idea (not sure its the best practice) is to first add a column to this user, called "role" so the user object will look like this : 我的想法(不确定最佳实践)是首先向该用户添加一列,称为“角色”,以便该用户对象如下所示:

{
    username: "John Doe",
    email: "john@doe.com",
    role: "Role1",
    createdAt : ...
    ...
}

and second, add this user to the role "Role1" using cloud code. 其次,使用云代码将此用户添加到角色“ Role1”。

Here is the cloud code: 这是云代码:

Parse.Cloud.afterSave(Parse.User, function(request, response) {
var user = request.user;
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.Role);
// user.role is undefined here !!!
query.equalTo("name", user.role);
query.first({ success: function(role) {
    role.relation("users").add(user);
    role.save();
} ,error: function(error){
    console.log('error');
    console.log(error); 
}});

}); });

As you can see in this code, i need to get the user role by its name using a query. 如您在这段代码中所看到的,我需要使用查询按名称获取用户角色。 the role is supposed to be stored in the user object, this is not the case in this code. 角色应该存储在用户对象中,而在此代码中并非如此。

Question : how can I access the role field in the cloud code ? 问题:如何访问云代码中的角色字段?

Thank you. 谢谢。

To get the role field we must use user.get('role') and not user.role 要获取role字段,我们必须使用user.get('role')而不是user.role

Notice: if you are using the 1.6.0 sdk the code will fail, consider changing the value to 1.5.0 in your ".parse.project" file, waiting for this bug to be fixed. 注意:如果使用1.6.0 sdk,则代码将失败,请考虑将“ .parse.project”文件中的值更改为1.5.0,等待此错误修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM