Home > Net >  how to add value into firebase field
how to add value into firebase field

Time:10-27

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?

CodePudding user response:

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(...); //            
  • Related