automatically updating data using cloud code in Parse.com

会有一股神秘感。 提交于 2019-12-03 16:36:56

@RoyH is 100% right to maintain your computed column as new objects are created. To do an initial migration, try a cloud function, like:

var _ = require("underscore");

Parse.Cloud.define("addFullnames", function(request, response) {
    // useMasterKey if the calling user doesn't have permissions read or write to Table
    Parse.Cloud.useMasterKey();
    var query = new Parse.Query("Table");
    // we'll call tables > 1000  an 'advanced topic'
    query.limit = 1000;
    query.find().then(function(results) {
        _.each(results, function(result) {
            var firstname = result.get("firstname") || "";
            var lastname = result.get("lastname") || "";
            result.set("fullname", (firstname + " " + lastname).trim());
        });
        return Parse.Object.saveAll(results);
    }).then(function(results) {
        response.success(results);
    }, function(error) {
        response.error(error);
    });
});

Call it like this:

curl -X POST \
  -H "X-Parse-Application-Id: your_app_id_here" \
  -H "X-Parse-REST-API-Key: your_rest_key_here" \
  -H "Content-Type: application/json" \
  https://api.parse.com/1/functions/addFullnames

You can factor out the code inside _.each() to make a function that's called here and by a beforeSave hook to maintain the data as it is added.

Yes, you can either just put a value for "fullname" when you are saving "firstname" and "lastname" (before cloudcode). Alternately, you can use the before save/ after save cloudcode functions to insert a value into that column:

Take a look at:

https://parse.com/docs/cloud_code_guide#webhooks-beforeSave https://parse.com/docs/cloud_code_guide#webhooks-afterSave

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