I have a cloud function in Firebase, and it updates an array inside a document using this method: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
However, when I try to then get the updated version of the document, it displays what it was before then array update. Here is my code:
eventUpdated is not showing the correct version before the array update.
if(isPut(request)){
//All new additions
const userId = request.body.userId;
const eventId = request.body.eventId;
const attStatus = request.body.attStatus;
try {
let eventsRef = db.collection('events').doc(eventId);
if (attStatus === true) {
// Add a new ID to the "eventAttendanceList" array field.
let arrUnion = eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayUnion(userId)
});
// Remove a ID from the "eventNonAttendanceList" array field.
let arrRm = eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
else if (attStatus === false) {
// Add a new ID to the "eventNonAttendanceList" array field.
let arrUnion = eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayUnion(userId)
});
// Remove a ID from the "eventAttendanceList" array field.
let arrRm = eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
else {
//If you do anything other than true or false, it will just remove the userId from both attending and non-attending
let arrUnion = eventsRef.update({
eventAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
let arrRm = eventsRef.update({
eventNonAttendanceList: admin.firestore.FieldValue.arrayRemove(userId)
});
}
let eventUpdated = await db.collection('events').doc(eventId).get()
return response.status(200).json({status: "200", message: "Event RSVP successfully updated", event: eventUpdated.data()}).send;
} catch(err) {
return response.status(500).json({status: "500", message: "Event RSVP could not be updated"}).send;
}
} else {
return response.json({status: "ERR", message: "Please send a PUT request."}).send;
}