解析云代码保存关系

parse cloud code save relation

我正在开发一个使用 Parse 作为后端的朋友关系应用程序。当 Alice 向 Bob 发送好友请求时,她会生成类型为 70 的通知,其中她自己是 userA,Bob 是 userB。为方便起见,通知还有 nameA 和 nameB 作为字符串。

我正在尝试在 Cloud Code 上实现 AfterSave 功能。此函数应将 Bob 添加到 Alice 的 "potential friends list" 并将 Alice 添加到 Bob 的“潜在朋友列表”。由于某些原因,我只能将 Bob 添加到 Alice 的列表,而不能将另一个添加到。

这是我的代码:

Parse.Cloud.afterSave("Notification", function(request, response) {

var namnamA = request.object.get('nameA');
var namnamB = request.object.get('nameB');
var tytype = request.object.get('type');
var alice = Parse.User.current();
if (tytype === 70) {
var bobQuery = new Parse.Query("User");
bobQuery.equalTo("username", namnamB);
bobQuery.limit(1);
bobQuery.find().then(function(bobs){
    bobs.forEach(function(bobby) {

        var bobbysRelation = bobby.relation("potFriendsList");
        var alicesRelation = alice.relation("potFriendsList");
        alicesRelation.add(bobby);
        alice.save().then(function(obj){
            console.log("alice has a new potential friend" + obj);
            bobbysRelation.add(alice);
            bobby.save().then(function(obj){
                console.log("bobby has a new potential friend" + obj);
            },
            function(obj, error){
                console.log(error);
            }); 
        },
        function(obj, error){
            console.log(error);
        });


    });
});
}
});

我是 JS 的新手,我几个小时都无法完成这项工作。非常感谢您的帮助。

稍微清理了代码,并添加了 success() / error() 响应,我相信这就是它不起作用的原因。

Parse.Cloud.afterSave("Notification", function(request, response) {

    var tytype = request.object.get('type');
    if (tytype !== 70) return response.success();

    var alice = Parse.User.current();
    var alicesRelation = alice.relation("potFriendsList");

    // EDIT - query user this way...
    var bobQuery = new Parse.Query(Parse.User);
    bobQuery.equalTo("username", request.object.get('nameB'));

    bobQuery.first().then(function(bob) {
        var bobsRelation = bob.relation("potFriendsList");

        alicesRelation.add(bob);
        bobsRelation.add(alice);

        return Parse.Object.saveAll([alice, bob]);

    }).then(function() {
        console.log("success " + arguments);
        response.success(arguments);
    }, function(error) {
        console.log("error " + error.message);
        response.error(error);
    });
});

其他一些注意事项:(0) 立即免除非 tytype==70 情况,(1) query.first() 将只得到第一个结果,因此不需要 limit(1) 并迭代,(2) Parse.Object.saveAll() 将保存一个对象数组,这很有用,因为您有两个对象。