首页 > 解决方案 > Firebase 删除字段中的特定内容

问题描述

我是本机反应的新手,我正在尝试删除特定字段但遇到问题

火力基地

我正在尝试删除 FriendList 中的 cm0IF5KopLgxnJTUtfi403kJuMl2

这是我的代码:

export default function deletefriends(FriendsUID){

    const friendremove = async() =>{

        // get current users uid
        const Uid = firebase.auth().currentUser.uid

        // define the current users 
        const currentUID = firebase.firestore().collection('users').where(
            "UID", "==", firebase.auth().currentUser.uid).get();
           
        // add the other users uid to current users friendlist
        currentUID.then((querySnapshot) => 

        {querySnapshot.forEach((doc) => {doc.ref.update(

            {FriendsList:FriendsUID.delete()})
        })
    })
    

    }

如何删除 FriendsUID?

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


因为您使用的是 ID 映射而不是数组,所以您需要将代码更改为(省略不相关的部分):

(doc) => {
  const friendsListMap = doc.get('FriendsList');
  delete friendsListMap[uidToDelete];
  return doc.ref.update({ FriendsList: friendsListMap });
}

或者

(doc) => {
  return doc.ref.update({
    [`FriendsList.${uidToDelete}`]: firebase.firestore.FieldValue.delete()
  });
}

您应该更新您的代码以正确地将 Promise 链接在一起(有些是浮动的,使用querySnapshot.docs.mapand Promise.all)并考虑使用事务来执行这些更改,这样您就可以确保数据不会被错误地删除。


推荐阅读