Search code examples
javascriptparse-platformparse-cloud-code

Delete pointer property in cloud code


Upon deleting an object from the class "MyModel", the code below is attempting to delete two objects related to it via pointer attributes, one called "colors" and one called "goal". Those objects are present in the data, but the logs indicate an "object not found" error.

Code originates from this answer.

Cloud Code:

function deleteMyModelPointer(myModel, pointerName, pointerClass) {
        var pointer = myModel.get(pointerName);
        if (pointer) {
            var query = new Parse.Query(pointerClass);
            return query.get(pointer).then(function(relatedObject) {
                return relatedObject.destroy();
            });
        } else {
            return null;
        }
    }

    Parse.Cloud.beforeDelete("MyModel", function(request, response) {
        var myModel = request.object;
        deleteMyModelPointer(myModel, "colors", "ColorModel").then(function() {
            return deleteMyModelPointer(myModel , "goal", "Goal");
        }).then(function() {
            response.success();
        }, function(error) {
            response.error(error);
        });
    });

Log:

v14 before_delete triggered for MyModel for user wMgAGMOPNK: Input: {"object":{"ACL":{"wMgAGMOPNK":{"read":true,"write":true}},"colors":{"__type":"Pointer","className":"ColorModel","objectId":"Z3gEplJ0tq"},"counter":1,"createdAt":"2015-12-10T14:06:19.630Z","createdAtLocally":{"__type":"Date","iso":"2015-12-10T14:06:18.825Z"},"deletedLocally":false,"goal":{"__type":"Pointer","className":"Goal","objectId":"BkruZqhyJ7"},"lastModifiedAt":{"__type":"Date","iso":"2015-12-10T14:06:24.270Z"},"objectId":"LuobH2P8iz","resetValue":0,"stepBy":1,"title":"Ggggggg","updatedAt":"2015-12-10T14:06:24.670Z","user":{"__type":"Pointer","className":"_User","objectId":"wMgAGMOPNK"}}} Result: {"code":101,"message":"Object not found."}

But both pointers are still there both from the object browser and from the client. As I said the ACL is set to the logged in PFUser for all 3 objects (with read, write permissions).


Solution

  • The problem is that the OP code is written for an objectId property, not a pointer. With an objectId in hand, the correct action is a query.get() to get the related object, but for a pointer, one needs only to fetch the pointer (and doesn't need to know its class).

    function deleteMyModelPointer(myModel, pointerName) {
        var pointer = myModel.get(pointerName);
        if (pointer) {
            return pointer.fetch().then(function(relatedObject) {
                return relatedObject.destroy();
            });
        } else {
            return null;
        }
    }
    

    Caller side can remain the same, just drop the third parameter.