Search code examples
flutterfirebaselistgoogle-cloud-firestore

Add a List of Document References into a flutter/firebase document field


I got this code:

  var testList = <String>[];

  await db
      .collection('tests')
      .where('user', arrayContainsAny: [db.doc('users/' + uid)])
      .get()
      .then((value) {
        value.docs.forEach((element) {
          testList.add(element.id);
        });
      });

  for (final test in testList) {
    print(test);
  }

this runs smoothly and i get a testList of 2 test ids. Later i am trying this:

        final testCollectionEntries = {
          'tests': db.doc('tests/' + testList),
          'name': testCollectionName
        };

        await db.collection("testsCollection").add(testCollectionEntries );

tests is a field type of a List of Document References in firebase. How can i make a list of Document References in order to use it to this code.


Solution

  • I found this as an answer. You need to make your code like this instead:

    final testCollectionEntries = {
        //'tests': db.doc('tests/' + testList), //REMOVE THIS IN ORDER TO USE UPDATE LATER
        'name': testCollectionName
        };
           
    DocumentReference testRef = //ADD THIS VAR
       await db.collection("testsCollection").add(testCollectionEntries);
    
    await db
        .collection('test')
        .where('user', arrayContainsAny: [db.doc('users/' + uid)])
        .get()
        .then((value) {  //USE THEN FOR ITERATION
          value.docs.forEach((element) {
            print(db.doc('tests/' + element.id));
            testRef.update({
              'examinerList':
                  FieldValue.arrayUnion([db.doc('examiners/' + element.id)]) //DONT FORGET BRACKETS []
            });
          });
        });