I've been working with Firestore using the code snippet provided in this link. However, I keep encountering an error that says Object is possibly 'undefined' when trying to access data.name. I'm confident that the document does contain a name field. Any suggestions on how I can resolve this issue?
// Monitoring changes to any `user` document.
exports.countNameChanges = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
// Retrieve current and previous values
const data = change.after.data();
const previousData = change.before.data();
// Proceed only if there's a change in name.
// Crucial to prevent infinite loops.
if (data.name == previousData.name) return null;
// Get the current count of name changes
let count = data.name_change_count;
if (!count) {
count = 0;
}
// Promise a set operation to update the count
return change.after.ref.set({
name_change_count: count + 1
}, {merge: true});
});