Reputation: 47
i got the following code:
const db = firebase.firestore();
var duettsRef = db.collection("duetts");
export const keyExists = (setKey)=>{
duettsRef.where("key", "==", setKey).where("player2", "==", "").get().then(querySnapshot => {
console.log(querySnapshot);
if (!querySnapshot.empty) {
this.db.collection('duett').set
({
player2: firebase.auth().currentUser.uid,
});
}
})
}
I logged the snapshot, and its working good untill this point. The "key" is unique, so the snapshot is either empty or finding one document with this specific properties. Screenshot of my firestore structure. What is not working, that I want if the snapshot is not empty, to edit the "player2" field in the found document, and set it to the current user id. So for example, if I search for the key:2jskmd21, it would fill the User ID in the player2 field: Like this. How do I do this correctly?
Upvotes: 0
Views: 57
Reputation: 4164
For this situation, you will want to use .update()
rather than .set()
. This is because the update method is designed to update values in a document while set requires a merge: true
flag however its primary function is to create a document if it doesn't exist which can be counterproductive.
In this code, I am setting the value as you described and by setting the limit to 1, will retrieve only 1 document.
const db = firebase.firestore();
var duettsRef = db.collection("duetts");
export const keyExists = (setKey)=>{
duettsRef.where("key", "==", setKey)
.where("player2", "==", "").limit(1).get()
.then(querySnapshot => {
console.log(querySnapshot);
if (!querySnapshot.empty) {
querySnapshot.docs[0].ref.update({
player2:firebase.auth().currentUser.uid});
}
})
.catch(e => console.log(e));
}
Upvotes: 1