I have an array in firebase called messages that stores objects that looks like:
{
userId: userId,
messageDocumentId: messageDocumentId,
unreadMessages: 0,
}
I am trying to change the value of the unreadMessages field whose value I will use in a React component.
Since firestore does not support updating fields of an array element object, I tried to delete the object that is in the array for a corresponding userId and add another object with updated unreadMessages field value like:
const resetMyMessageObject = async() => {
if (messageDocumentId) {
const messageObject = getSendersMessageObject();
if (messageObject !== undefined) {
const docRef = db.collection('users').doc(currentUser.uid);
async docRef.update({
messages: firebase.firestore.FieldValue.arrayUnion({
userId: selectedUid,
messageDocumentId: messageDocumentId,
unreadMessages: 0,
}),
})
async docRef.update({
messages:
firebase.firestore.FieldValue.arrayRemove(messageObject),
});
}
}
};
It does not add a document sometimes but will delete the old object in the array. I also tried chaining the update to delete in a .then after the update to add a new object in the array but it is not working as expected at all times. Could there be other ways to do what I am trying to achieve?