【问题标题】:How to add data on nested array in Firestore with react-native如何使用 react-native 在 Firestore 中的嵌套数组上添加数据
【发布时间】:2021-07-15 21:07:29
【问题描述】:

我想问是否可以在嵌套数组中添加数据。我想要的结果是这个

但是当我使用我使用的代码添加新评级时我会得到这个

async function getAll(){
    const userEmail= firebase.firestore().collection('users')
    const snapshot=await userEmail.where('email','==',index.email).get()
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }  
    
    snapshot.forEach(doc => {
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({parking:[markerName]})},{merge:true})
      userEmail.doc(doc.id).set({userRatings2:firebase.firestore.FieldValue.arrayUnion({rating:[currentRating]})},{merge:true})

     
      
     console.log(userEmail.doc(doc.id));
    });
  }
  getAll()

【问题讨论】:

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


    【解决方案1】:

    不幸的是,在 Firebase Firestore 中,您甚至无法更改特定 index 处的简单数组值。这也意味着您不能保存嵌套数组值。您可以在 answer 上阅读更多相关信息。

    唯一的方法是下载整个数组进行修改并将整个数组再次保存到数据库中。您的应用程序没有太多上下文,所以我不知道这对您来说是否是一个好的解决方案。这取决于数组中有多少数据。

    【讨论】:

    • 是的,我试过这种方式,效果很好。非常感谢!
    【解决方案2】:

    我已经设法通过将 forEach 函数用于图像路径数组来做到这一点

      const [imageUri, setImageUri] = useState([]);
      const [uploading, setUploading] = useState(false);
    
      const UploadImage = () => {
        setUploading(true);
        imageUri.forEach(async (image, index) => {
          // setTransferred(0);
    
          const pathToFile = image;
          let filename = pathToFile.substring(pathToFile.lastIndexOf('-') + 1);
          const extension = filename.split('.').pop();
          const name = filename.split('.').slice(0, -1).join('.');
          filename = name + Date.now() + '.' + extension;
    
          const reference = storage().ref().child(`/userprofile/${filename}`);
          // path to existing file on filesystem
    
          // uploads file
          const task = reference.putFile(pathToFile);
          try {
            await task;
    
            const url = await reference.getDownloadURL();
            downloadableURI.push(url);
            if (index == imageUri.length - 1) {
              setUploading(false);
              Alert.alert(
                'Image uploaded!',
                'Your image has been uploaded to the Firebase Cloud Storage Successfully!',
              );
            }
          } catch (e) {
            console.log(e);
          }
        });
      };
    
    

    每当调用该函数时,图像数组就会上传到 Firebase 存储中,

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多