Parse cloud code - modifying all PFUsers

狂风中的少年 提交于 2019-12-13 05:04:15

问题


I'm trying to create a cloud Job that takes the users full name or username and saves it in lower case in another column. here's what I have so far:

Parse.Cloud.job('normaliseUsername',function(request, status) {

    Parse.Cloud.useMasterKey();

    var query = new Parse.Query(Parse.User);
    query.find({
        success: function(items){

            for (var i=0;i<items.length;i++) {
                var user = items[i];
                console.log(user);
                var changed = user["nameChanged"];
                if (changed === true) {
                    var username = user.username;
                    user.set("lowerCaseName",username.toLowerCase());
                } else {
                    var realName = user["firstName"] + " " + user["lastName"];
                    user.set("lowerCaseName",realName.toLowerCase());
                }
                user.save();
            }

        }
    });
});

This results in a new column, lowerCaseName, full of undefined.

how do I access properties of a PFUser in this instance? I have tried using user.get(''); but it says Cannot call method 'get' of undefined


回答1:


Do it this way :

Parse.Cloud.job("normaliseUsername", function(request, status) {
    Parse.Cloud.useMasterKey();
    var count_user = 0;
    var query = new Parse.Query(Parse.User);
    query.descending('updatedAt');  
    query.Exist('nameChanged'); 
    query.limit(1000);  
    return query.find().then(function(users) {
        return Parse.Promise.when(users.map(function(user) {
            count_user+= 1;
            if (user.get("nameChanged")) {
                user.set("canonical_firstname", user.get("username").toLowerCase());
            } else {
                var realName = user.get("firstname") + ' ' + user.get("lastname");
                user.set("lowerCaseName", realName.toLowerCase());                              
            }
            return user.save();
        }));
    }).then(function() {
        status.success("normaliseUsername with " + count_user + " user(s) updated.");
    }, function(error) {
        status.error("Uh oh, something went wrong.");
    });
});

Your loop with for, will never works, you need to use Promise. More information here : http://blog.parse.com/learn/engineering/whats-so-great-about-javascript-promises/

The way the above script works, you will work with Promise in Parallel, not in Series : https://parse.com/docs/js/guide#promises



来源:https://stackoverflow.com/questions/31113850/parse-cloud-code-modifying-all-pfusers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!