I have been trying to update a nested object in Firestore when a cloud function is triggered as described in the documentation.
Here's the onCreate trigger:
// Cloud function to increment count total product reviews
exports.incTotalProductReviews = functions.firestore
.document("users/{uid}/productReviewRequests/{productReviewReq}")
.onCreate((snap, context) => {
// Get the userID & eventID from context
const userID = context.params.uid;
const eventId = context.eventId;
const data = snap.data()
// Get doc ref
const userStatisticsRef = admin.firestore().collection("userStatistics").doc(userID);
const eventRef = admin.firestore().collection("pastEvents").doc(eventId)
return eventRef.get()
.then((doc) => {
//Check for rerun - idempotent function
if (doc.exists) {
return functions.logger.log("Event already happened.");
} else {
return userStatisticsRef.update({
"productReview.REQUESTED": admin.firestore.FieldValue.increment(1)
})
}
})
.then(() => eventRef.set({ timestamp: admin.firestore.Timestamp.now() }))
.catch((err) => { functions.logger.error(err) });
});
The result is that the nested object does not update, instead a new field with the key "productReview.REQUESTED" is created and updated.
My goal was to use a dynamic key as described in this answer, but it had the same effect.
Is there something that I'm doing wrong, or is it a bug in Firestore/Cloud functions?
UPDATE
So I tried various approaches and it finally worked - kinda. (only for update() method, not set())
Using
.set({"productReview.REQUESTED": admin.firestore.FieldValue.increment(1)}, {merge: true})
has the same effect as described in the question, i.e. the nested field does not update, instead a new field with the keyproductReview.REQUESTED
is created and updated. This is a problem since I want to update a document but there is no guarantee that the document exists.Using the
.update({"productReview.REQUESTED": admin.firestore.FieldValue.increment(1)})
worked finally (it didn't before) - but the drawback being that now I have to check if the document exists/ensure that the document exists.