【问题标题】:Firebase remove specific in a the fieldFirebase 删除字段中的特定内容
【发布时间】:2021-12-21 19:20:34
【问题描述】:

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

我正在尝试删除 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?

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    因为您使用的是 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.mapPromise.all)并考虑使用 transaction 来执行这些更改,这样您就可以确保数据不是被误删了。

    【讨论】:

      【解决方案2】:

      如果您尝试从FriendsList 数组中删除单个项目,则需要arrayRemove 操作。来自updating items in an array的文档:

      await washingtonRef.update({
          regions: arrayRemove("east_coast")
      });
      

      【讨论】:

      • 嗨,弗兰克,我使用了 {FriendsList: firebase.firestore.FieldValue.arrayRemove(FriendsUID)}),它可以工作,但它删除了 FriendsList 中的所有内容。我只需要删除一个。我该怎么做?
      • 另外,FriendList是一个map,运行remove函数后变成数组,变成空的。
      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      相关资源
      最近更新 更多