Skip to content Skip to sidebar Skip to footer

Parse Cloud - Delete Property (pointer)

My data model consist of 3 objects, two of them (the children) are linked to the parent using a pointer. MyModel is the parent that has 2 properties: colors and goal. Both are poi

Solution 1:

Lets break this into smaller functions and correct a couple problems in the OP code along the way. It's very helpful to reduce things to smaller, promise-returning functions keep the code modular and the concurrency manageable.

EDIT Generally, it's preferred to use pointers to relate objects. Here's a general purpose function to delete an object related via pointer:

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

Some authors relate objects via a string column containing the id of the related object. Here's the equivalent function to delete an object related by id:

functiondeleteRelatedId(myModel, columnName, relatedClass) {
    var relatedId = myModel.get(columnName);
    if (relatedId) {
        var query = newParse.Query(relatedClass);
        return query.get(relatedId).then(function(relatedObject) {
            return relatedObject.destroy();
        });
    } else {
        returnnull;
    }
}

Now, the beforeDelete method is easy to write and understand. (Assuming the relationships via pointers):

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

The other important thing to notice is that the before hook takes a response object and is required to invoke success / error on that object after the related tasks are complete.

All of this hinges on promises, which are necessary and immensely useful. Read about parse's implementation of them here.

Post a Comment for "Parse Cloud - Delete Property (pointer)"