Paul Peelen
Paul Peelen

Reputation: 10329

Parse updating a set of objects

I have trouble updating a set of values in my cloud code. I have tried .save() seperately and .saveAll() but the class doesn't get updated in Parse and I get errors returned.

What I am trying to do is to get all messages from class ChatMessages which has a pointer to the Parse user and Chat class. When the method is called, the class column readAt needs to be updated to the current date. I call my method from an iOS (objective-C) app.

This is the latest version of my method:

Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
    var errorMsg;
    var roomName;

    var _ = require('underscore.js');

    var userPointer = new Parse.User.current();

    if (!request.params.roomName) {
        errorMsg = "Chat room needs to be identified";
    } else {
        roomName = request.params.roomName;
    }

    console.log("Checking chats for userID: " + userPointer.id);

    if (!userPointer.id) {
        var emptyUserMsg = "User has to be provided";
        if (errorMsg) {
            errorMsg = errorMsg + emptyUserMsg;
        } else {
            errorMsg = emptyUserMsg;
        };
    }

    if (errorMsg) {
        response.error(errorMsg);
    }

    var chatQuery = new Parse.Query("Chat");
    chatQuery.equalTo("roomName", roomName);
    chatQuery.find({
        success: function(results) {
            if (results.length > 0) {
                var chat = results[0];

                console.log("Found chat with ID: "+chat.id);

                var chatMessagesQuery = new Parse.Query("ChatMessage");
                chatMessagesQuery.equalTo("chat", chat);
                chatMessagesQuery.notEqualTo("fromUser", userPointer);
                chatMessagesQuery.equalTo("readAt", undefined);

                chatMessagesQuery.find().then(function(chatMessagesQueryResults) {
                    _.each(chatMessagesQueryResults, function(result) {
                        result.set("readAt", new Date());
                        console.log("Setting readAt for chat message " + result.id + " which has toUser " + result.get("toUser"));
                    });
                    return Parse.Object.saveAll(chatMessagesQueryResults,{
                        success: function(list) {
                           console.log("Success updating objects");
                        },
                        error: function(error) {
                           console.log("Error updating objects: " + error);
                        },});
                }).then(function(results) {
                    response.success(results);
                    console.log("Update for reatAt for chat is successfull");
                }, function(error) {
                    response.error(error);
                    console.log(error);
                });
            } else {
                response.error("No rooms found");
                console.log("No rooms found");
            }
        },
        error: function(error) {
            response.error("Room name not found");
            console.log(error);
        }
    });

});

Log output:

E2015-07-19T09:13:48.483Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
  Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
  Result: {"code":101,"message":"object not found for update"}
I2015-07-19T09:13:48.540Z]Checking chats for userID: CZwQL4y751
I2015-07-19T09:13:48.593Z]Found chat with ID: gfvAkirqTs
I2015-07-19T09:13:48.647Z]Setting readAt for chat message ZiWUIdUtUm which has toUser undefined
I2015-07-19T09:13:48.648Z]Setting readAt for chat message YHEBLpR04U which has toUser undefined
I2015-07-19T09:13:48.649Z]Setting readAt for chat message 0wZ4LQd8ZC which has toUser undefined
I2015-07-19T09:13:48.650Z]Setting readAt for chat message MYsYGyXI0k which has toUser undefined
I2015-07-19T09:13:48.751Z]Error updating objects: [object Object]
I2015-07-19T09:13:48.752Z]{"code":101,"message":"object not found for update"}
E2015-07-19T09:13:49.042Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
  Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
  Result: {"code":101,"message":"object not found for update"}

Class:

The parse class

Upvotes: 3

Views: 632

Answers (1)

danh
danh

Reputation: 62676

The query can be vastly simplified by making a chatMessages query relational to chats matching the user and room criteria. The code structure can be improved by not mixing callback and promise styles, and by separating logical chunks into small, promise-returning functions.

Stripping away some of the debug instrumentation you added, we get (untested, of course)...

function unreadChatMessagesInRoom(roomName, excludeUser) {
    var query = new Parse.Query("ChatMessage");
    query.notEqualTo("fromUser", excludeUser);
    query.doesNotExist("readAt");

    var chatQuery = new Parse.Query("Chat");
    chatQuery.equalTo("roomName", roomName);
    query.matchesQuery("chat", chatQuery);

    return query.find();
}

Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {    
    var _ = require('underscore.js');
    var user = request.user;

    unreadChatMessagesInRoom(request.params.roomName, user).then(function(chatMessages) {
        console.log(chatMessages.length + " chat messages found");
        _.each(chatMessages, function(chatMessage) {
            chatMessage.set("readAt", new Date());
        });
        return Parse.Object.saveAll(chatMessages);
    }).then(function(results) {
        response.success(results);
    }, function(error) {
        response.error(error);
    });
});

Upvotes: 3

Related Questions