Search code examples
parse-platformparse-serverparse-cloud-code

In Parse server get() method causes crash


I have a find query with include to get pointer data. It's working fine but if the pointer object does not exist then server crashes.

Here is my query:

var repliesQuery = new Parse.Query("Reply");
repliesQuery.include("author");
repliesQuery.find({
    useMasterKey: true
}).then(function(foundMessages) {
    var results = [];
    for (var i = 0; i < foundMessages.length; i++) {
        var rp = {};
        rp.title = foundMessages[i].get("title");
        rp.description = foundMessages[i].get("description");

        var author = foundMessages[i].get("author");
        rp.authorId = author.id;

        results.push(rp);
    }
    promise.resolve(results);
});

Everything works fine when the author exists, but if it does not exist then the server crashes.

I tried to add this:

if (author.hasOwnProperty('id')) {
    rp.authorId = author.id;
}

But still the issue is not resolved.

Is there any way we can fix this issue?


Solution

  • It's most likely because you're accessing a property of an undefined object, in this case author, in line

    rp.authorId = author.id

    Like Davi suggests, include a check if author exists.

    var repliesQuery = new Parse.Query("Reply");
    repliesQuery.include("author");
    repliesQuery.find({
        useMasterKey: true
    }).then(function(foundMessages) {
        var results = [];
        for (var i = 0; i < foundMessages.length; i++) {
            var rp = {};
            rp.title = foundMessages[i].get("title");
            rp.description = foundMessages[i].get("description");
    
            var author = foundMessages[i].get("author");
            if (author) {
                rp.authorId = author.id;
            }
    
            results.push(rp);
        }
        promise.resolve(results);
    });
    

    Your check

    if (author.hasOwnProperty('id')) {
        rp.authorId = author.id;
    }
    

    also accesses a property of author, so again it would throw an error if author is undefined.