addDocument method

Future<String?> addDocument(
  1. List<String> paths,
  2. Map<String, dynamic> update
)

Adds a new document into the collection in Firebase.

paths is the list of paths to the document. For example: myCollection, documentId, mySubCollection which will be constructed to myCollection/documentId/mySubCollection. Last item in paths must be collection. update is the data which will be added to the document.

Implementation

Future<String?> addDocument(List<String> paths, Map<String, dynamic> update) async {
  assert(
      paths.length % 2 == 1,
      'paths must be uneven number since it has to point to the collection. If you want'
      'to include specific documentId, use [addDocumentWithId] method.');

  try {
    if (_includeAdditionalFields) _includeAdditionalFieldsIntoMap(update, includeCreatedAt: true);

    final pathToDocument = paths.join('/');
    final documentReference = await _firebaseFirestore.collection(pathToDocument).add(update);
    _loggingService.log('FirestoreHelper.addDocument: Path: $pathToDocument, Update: $update');

    return documentReference.id;
  } catch (e, s) {
    _loggingService.log(
      'FirestoreHelper.addDocument: Failed. Path: $paths, Update: $update, Exception: ${e.toString()}. StackTrace: $s',
      logType: LogType.error,
    );
    return null;
  }
}