简体   繁体   中英

How to save a many-to-many Relation in Parse using Cloud code?

Basically, in my users table, I have a column canHave which is a list of objects Event . So I have a many-to-many relationship between my Users and Event tables

Here is my code (Cloud code) :

  Parse.Cloud.define("updateUserCanHave", function (request, response) {
    var query = new Parse.Query(Parse.User);
    query.equalTo("email", request.params.mail);
    query.find({
        success: function (myUser) {

            var newUser = myUser[0];
            var myRelation = newUser.relation("canHave");

            var eventsQuery = newUser.relation('canHave').query();
            eventsQuery.find().then(function (events) {
                myRelation.remove(events[0]);
            });

            newUser.save(null, {useMasterKey: true})
            response.success();
        }
    }).catch(function (error) {
        response.error("Error " + error.code + " : " + error.message + " when updating user canHave.");
    });
});

But my user never change and my function's parameters are good.

newUser.save() will begin to execute asynchronously, then be immediately terminated by the synchronous call to response.success() . Fix by placing the response in execution sequence after the save.

I prefer the promise-returning form for these calls, but if your style is callback functions...

newUser.save(null, {
    useMasterKey: true,
    success: function(result) {
        // moved here, after the save succeeds
        response.success(result);
    },
    error: function(result, error) {
        response.error(error);
    }
});

EDIT The code has the same problem on the relational query. It's too hard to make this clear (or even see problems) with callback style methods. Employing promises...

function findUserByEmail(email) {
    let query = new Parse.Query(Parse.User);
    query.equalTo("email", email);
    return query.first();  // notice "first" here, if we're going to use only the first anyway
}

Parse.Cloud.define("updateUserCanHave", function (request, response) {
    var user;
    findUserByEmail(request.params.mail).then(_user => {
        user = _user;
        return user.relation("canHave").query().first();
        // I left your relation query in here.  In general, you don't
        // have to query before removing it, but maybe your app logic requires this
        // in other words, you could just do the remove and save here, and skip the next then block
    }).then(event => {
        if (event) user.relation("canHave").remove(event);
        return user.save(null, { useMasterKey: true });
    }).then(() => {
        response.success();
    }).catch(error => {
        response.error(error);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM