0

I'm new to react native and firebase, and trying to create a social media app, building up a adding friend feature.

I'm trying to add UID into the current user's database here is my code :


    const friendadd = async() =>{

        
       // get the users field
        const friendlist = firebase.firestore().collection('users').where("UID", "==", firebase.auth().currentUser.uid).get();

        const addfriend = await friendlist.update({
            "FriendsList.yVHnHIqhsOYbVbWOM6TbjpU4N3x1":true
        })

        
    }
    friendadd()


}

and this is what my firebase looks like Firebase

by using the code above, it doesn't update the field somehow. but if I hard code the doc it will work :

const friendlist = firebase.firestore().collection('users').doc('CgQklWWClMJdoOvU4pEk')

how do I get the current user and update the field?

1 Answer 1

1

To add an entry to your FriendsList field, you can use an arrayUnion operation:

friendlist.update({
  FriendsList: firebase.firestore.FieldValue.arrayUnion({
    uid: "uidOfItemToAdd",
    bio: "bioOfItemToAdd"
  })
});

Update: This code sets friendlist to a Promise<QuerySnapshot>:

const friendlist = firebase.firestore().collection('users').where("UID", "==", firebase.auth().currentUser.uid).get();

To process these documents and update each of them:

friendlist.then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    doc.ref.update(...); // 👈 here goes the same code as above
  });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Frank, I tried this way, but still didn't update. I'm wondering if its because const friendlist = firebase.firestore().collection('users').where("UID", "==", firebase.auth().currentUser.uid).get(); this line? it didn't get into the doc?
Because if i hard code the .doc, it will update. const friendlist = firebase.firestore().collection('users').doc('CgQklWWClMJdoOvU4pEk'). how do i get the current document?
Yeah, that won't work. I updated the code in my answer, but strongly recommend spending some time in the documentation on processing queries: firebase.google.com/docs/firestore/query-data/…, or in the codelab: firebase.google.com/codelabs/firestore-web
Thank you so much. for the update, is there a way to locate other people's uid? and add it to current users FriendsList?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.