I've made a chat app and I want the user to be able to mark chatroom as favourite or mute the chatroom.
The structure of my database is like the image below
What I want is when user is trying to mute a chatroom or mark it as favourite, I only update the item that matches the chatroomId, But after a lot of searching, I found out Firebase won't allow you to update an element of an array and you can only add or remove from an array.
This is my function to mute or mark a chatroom as favourite:
static final Firestore dbReference = Firestore.instance;
static Future<void> currentUserChatroomChangeMuteOrFavouriteMethod({
@required String chatroomId,
@required bool muteValue,
@required bool favouriteValue,
@required ChatroomMuteFavouriteOption operationToBeDone,
}) async {
DocumentReference docRef = dbReference
.collection("user_chatrooms")
.document(CurrentUserDetails.id);
DocumentSnapshot docSnapshot = await docRef.get();
Map<String, dynamic> docData = docSnapshot.data;
List<Map<String, dynamic>> userChatrooms =
(docData["chatrooms"] as List<dynamic>)
.map((chatroom) => Map<String, dynamic>.from(chatroom))
.toList();
for (int index = 0; index < userChatrooms.length; index++) {
Map<String, dynamic> chatroom = userChatrooms[index];
if (chatroom["chatroomId"] == chatroomId) {
if (operationToBeDone == ChatroomMuteFavouriteOption.muteOperation) {
chatroom["isMuted"] = !muteValue;
} else {
chatroom["isMarkedFavourite"] = !favouriteValue;
}
break;
}
}
await docRef.updateData({"chatrooms": userChatrooms});
}
So basically I get all the data, I update the field I want and I updateData again but this is not a good solution as I am also getting the chatrooms which I don't need.
How can I do this operation effeciently?
Thanks.
