create<T> method

void create<T>(
  1. DocumentReference<T> ref,
  2. T data
)

Create a document with the provided object values. This will fail the batch if a document exists at its location.

  • documentRef: A reference to the document to be created.
  • data The object to serialize as the document.

Throws if the provided input is not a valid Firestore document.

final writeBatch = firestore.batch();
final documentRef = firestore.collection('col').doc();

writeBatch.create(documentRef, {foo: 'bar'});

writeBatch.commit().then(() {
  print('Successfully executed batch.');
});

Implementation

void create<T>(DocumentReference<T> ref, T data) {
  final firestoreData = ref._converter.toFirestore(data);
  _validateDocumentData('data', firestoreData, allowDeletes: false);

  _verifyNotCommited();

  final transform = _DocumentTransform.fromObject(ref, firestoreData);
  transform.validate();

  final precondition = Precondition.exists(false);

  firestore1.Write op() {
    final document = DocumentSnapshot._fromObject(ref, firestoreData);
    final write = document._toWriteProto();
    if (transform.transforms.isNotEmpty) {
      write.updateTransforms = transform.toProto(firestore._serializer);
    }
    write.currentDocument = precondition._toProto();
    return write;
  }

  _operations.add((docPath: ref.path, op: op));
}