Search code examples
javascriptparse-platformparse-cloud-code

Parse new User save does not return new ID


When saving anew user in Parse, although the user saves correctly, the new user is not returned after the save, so the code errors at console.log("userResult id " + userResult.id);. If the user already exists, the save function returns the id correctly. Is this a bug with Parse or am I missing something?

    return userQuery
        .first(function (userResult) {
            if (!helpers.isDefined(userResult)) {
                userResult = new Parse.User();
                userResult.set("username", helpers.phoneToUsername(phoneNumber));
                userResult.set("password", helpers.generatePassword(phoneNumber));
                userResult.set("displayName", displayName);
            }
            userResult.set("location", location);
            userResult.set("smsVerified", false);
            return userResult.save()
        })
        .then(function (userResult) {
            console.log("userResult id " + userResult.id); <-- ERROR HERE
            user = userResult;
            return Verification.createSmsVerification(userResult);
        })...

The error:

Result: TypeError: Cannot read property 'id' of undefined
    var userQuery = new Parse.Query(Parse.User);
        userQuery.equalTo("username", helpers.phoneToUsername(phoneNumber));

Its as if the user is being saved after then then() callback, but this should not be the case.


Solution

  • After some time fiddling around in the dark on this, I've found that the problem is the initial code is within the first() callback rather than the thenable. Changing the top lines of code from first(function()... to first().then(function() has solved the problem.

    return userQuery.first()
            .then(function (userResult) {
                if (!helpers.isDefined(userResult)) {
                    userResult = new Parse.User();
                    userResult.set("username", helpers.phoneToUsername(phoneNumber));
                    userResult.set("password", helpers.generatePassword(phoneNumber));
                    userResult.set("displayName", displayName);
                }
                userResult.set("location", location);
                userResult.set("smsVerified", false);
                return userResult.save()
            })
            .then(function (userResult) {
                console.log("userResult id " + userResult.id); <-- ERROR HERE
                user = userResult;
                return Verification.createSmsVerification(userResult);
            })...