0
votes

I already make loop some function to save as a list to Firestore like below:

var documentAttachments = await Firestore.instance
          .collection('cs_candidates')
          .document(widget.userEntity.email)
          .collection('attachments')
          .document();

      for (FinalUrlModel data in result) {
        await Firestore.instance.runTransaction((transaction) async {
          await documentAttachments.setData(AttachmentsEntity(
            name: data.name,
            type: RESUME,
            urlName: data.url,
            url: AttachmentsHelper.validateUrl(data.url),
          ).toJson());
        });
      }

But when I try to save it and checked the data, the data that already saved it to Firestore only the last data. But actually I have 5 data as a list from result.

How to make different documentID so I can save all data without replaced the before data? Or have any idea to save a list without looping first?

Because I need save all data list from result to Firebase Storage.

1

1 Answers

0
votes

In your code, you are specifying .document(widget.userEntity.email) and setData will add the document at that reference. If you want different(random) documentId , don't pass anything in document().That should work.

var documentAttachments = await Firestore.instance
      .collection('cs_candidates')
      .document()
      .collection('attachments')
      .document();

If you don't want random documentId, you can try appending some data at the end of documentId so it becomes unique.

Or you can use sub-collections

for (FinalUrlModel data in result) {
    await Firestore.instance.runTransaction((transaction) async {
      await documentAttachments.collection('some-collection').document().setData(AttachmentsEntity(
        name: data.name,
        type: RESUME,
        urlName: data.url,
        url: AttachmentsHelper.validateUrl(data.url),
      ).toJson());
    });
  }

I hope this helps!

Update:

Just move the documentAttachments inside a for loop like this:

for (FinalUrlModel data in result) {
        var documentAttachments = await Firestore.instance
            .collection('cs_candidates')
            .document(widget.userEntity.email)
            .collection('attachments')
            .document();

        await Firestore.instance.runTransaction((transaction) async {
          await documentAttachments.setData(AttachmentsEntity(
            name: data.name,
            type: RESUME,
            urlName: data.url,
            url: AttachmentsHelper.validateUrl(data.url),
          ).toJson());
        });
      }

So it will always generated documentId based on the number of lists.