首页 > 解决方案 > 将文档添加到 Cloud Firestore 中的集合而不覆盖以前的文档 Flutter

问题描述

在我的颤振应用程序中,我需要将文档添加到集合“influencerPost”中,并且每次用户添加新的“帖子”时,都必须将这个文档添加到之前的文档中……但是此时我只是覆盖了之前的文档。正如您通过我的方法所看到的,我有uploadImage未来会拾取图像并将其存储到 Firebase 中的存储中。之后我创建了一个名为的集合 influencerPost,每次新帖子生成新文档时我都必须添加而不覆盖

这是完整的代码:

Future uploadImage(BuildContext context) async {
    String fileName = basename(_postImage.path);
    Reference firebaseStorageRef =
        FirebaseStorage.instance.ref().child('postImage/$fileName');
    UploadTask uploadTask = firebaseStorageRef.putFile(_postImage);
    TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
    final String downloadUrl = await taskSnapshot.ref.getDownloadURL();
    await FirebaseFirestore.instance
        .collection('influencerPost')
        .doc(firebaseUser.uid)
        .set({
      "imageUrl": downloadUrl,
      'postText': IfUserProfile.post
    });
    setState(() => CircularProgressIndicator());
  }

通过这种方式,我得到了所有文件,但文件被覆盖,而不是我需要保留以前的文件并添加一个新文件。

标签: firebasefluttergoogle-cloud-firestore

解决方案


由于您想针对用户维护多个帖子,因此您必须创建子集合。检查下面的代码,我在其中添加了子集合 .collection("post")

    Future uploadImage(BuildContext context) async {
    String fileName = basename(_postImage.path);
    Reference firebaseStorageRef =
        FirebaseStorage.instance.ref().child('postImage/$fileName');
    UploadTask uploadTask = firebaseStorageRef.putFile(_postImage);
    TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
    final String downloadUrl = await taskSnapshot.ref.getDownloadURL();
    await FirebaseFirestore.instance
        .collection('influencerPost')
        .doc(firebaseUser.uid)
        .collection("post")
        .add({
      "imageUrl": downloadUrl,
      'postText': IfUserProfile.post
    });
    setState(() => CircularProgressIndicator());
  }

推荐阅读