Reputation: 101
I am making an update to my document. I use the set method because I want to overwrite my fields. Therefore, when i do my set, it works perfectly, modifying the object in the firestore database. But i am not able to return the document afterward. The error I get:
Cannot read property 'exists' of undefined
at Firebase.js:127
Here is my code:
const updateItemFromCollection = async (collectionName, uid, data) => {
return database
.collection(collectionName)
.doc(uid)
.set(data, { merge: true })
.then(doc => {
if (!doc.exists) {
console.log("No such document!"); //Error
} else {
return doc.data();
}
})
.catch(error => {
console.log(error);
});
};
Upvotes: 1
Views: 2025
Reputation: 83093
This is because the set()
method returns a Promise<void>
and not a Promise<DocumentSnapshot<T>>
.
You will need to read the document again, as follows:
const updateItemFromCollection = async (collectionName, uid, data) => {
const docRef = database.collection(collectionName).doc(uid);
return docRef.set(data, { merge: true })
.then(() => {
return docRef.get();
.then(doc => {
if (!doc.exists) {
console.log("No such document!"); //Error
} else {
return doc.data();
}
})
.catch(error => {
console.log(error);
});
};
This is the way Firestore works, and AFAIK, it is based on the fact that you already know the value of the document fields, since you passed a corresponding object to set()
. One could remark however that this is not true for the values calculated in the back-end based on sentinel values, see FieldValue.
Upvotes: 3