BulkWriter

BulkWriter

new BulkWriter()

A Firestore BulkWriter that can be used to perform a large number of writes in parallel.

Methods

close() → {Promise.<void>}

Commits all enqueued writes and marks the BulkWriter instance as closed.

After calling close(), calling any method will throw an error. Any retries scheduled as part of an onWriteError() handler will be run before the close() promise resolves.

Returns a Promise that resolves when there are no more pending writes. The Promise will never be rejected. Calling this method will send all requests. The promise resolves immediately if there are no pending writes.

Returns:
Type Description
Promise.<void>

A promise that resolves when all enqueued writes up to this point have been committed.

Example
```
let bulkWriter = firestore.bulkWriter();

bulkWriter.create(documentRef, {foo: 'bar'});
bulkWriter.update(documentRef2, {foo: 'bar'});
bulkWriter.delete(documentRef3);
await close().then(() => {
  console.log('Executed all writes');
});
```

create(documentRef, data) → {Promise.<WriteResult>}

Create a document with the provided data. This single operation will fail if a document exists at its location.

Parameters:
Name Type Description
documentRef DocumentReference

A reference to the document to be created.

data T

The object to serialize as the document.

Returns:
Type Description
Promise.<WriteResult>

A promise that resolves with the result of the write. If the write fails, the promise is rejected with a BulkWriterError.

Throws:

If the provided input is not a valid Firestore document.

Type
Error
Example
```
let bulkWriter = firestore.bulkWriter();
let documentRef = firestore.collection('col').doc();

bulkWriter
 .create(documentRef, {foo: 'bar'})
 .then(result => {
   console.log('Successfully executed write at: ', result);
 })
 .catch(err => {
   console.log('Write failed with: ', err);
 });
});
```

delete(documentRef, preconditionopt) → {Promise.<WriteResult>}

Delete a document from the database.

Parameters:
Name Type Attributes Description
documentRef DocumentReference

A reference to the document to be deleted.

precondition Precondition <optional>

A precondition to enforce for this delete.

Properties
Name Type Attributes Description
lastUpdateTime Timestamp <optional>

If set, enforces that the document was last updated at lastUpdateTime. Fails the batch if the document doesn't exist or was last updated at a different time.

Returns:
Type Description
Promise.<WriteResult>

A promise that resolves with the result of the delete. If the delete fails, the promise is rejected with a BulkWriterError.

Example
```
let bulkWriter = firestore.bulkWriter();
let documentRef = firestore.doc('col/doc');

bulkWriter
 .delete(documentRef)
 .then(result => {
   console.log('Successfully deleted document');
 })
 .catch(err => {
   console.log('Delete failed with: ', err);
 });
});
```

flush() → {Promise.<void>}

Commits all writes that have been enqueued up to this point in parallel.

Returns a Promise that resolves when all currently queued operations have been committed. The Promise will never be rejected since the results for each individual operation are conveyed via their individual Promises.

The Promise resolves immediately if there are no pending writes. Otherwise, the Promise waits for all previously issued writes, but it does not wait for writes that were added after the method is called. If you want to wait for additional writes, call flush() again.

Returns:
Type Description
Promise.<void>

A promise that resolves when all enqueued writes up to this point have been committed.

Example
```
let bulkWriter = firestore.bulkWriter();

bulkWriter.create(documentRef, {foo: 'bar'});
bulkWriter.update(documentRef2, {foo: 'bar'});
bulkWriter.delete(documentRef3);
await flush().then(() => {
  console.log('Executed all writes');
});
```

onWriteError(shouldRetryCallback)

Attaches an error handler listener that is run every time a BulkWriter operation fails.

BulkWriter has a default error handler that retries UNAVAILABLE and ABORTED errors up to a maximum of 10 failed attempts. When an error handler is specified, the default error handler will be overwritten.

Parameters:
Name Type Description
shouldRetryCallback BulkWriter~shouldRetryCallback

A callback to be called every time a BulkWriter operation fails. Returning true will retry the operation. Returning false will stop the retry loop.

Example
```
let bulkWriter = firestore.bulkWriter();

bulkWriter
  .onWriteError((error) => {
    if (
      error.code === GrpcStatus.UNAVAILABLE &&
      error.failedAttempts < MAX_RETRY_ATTEMPTS
    ) {
      return true;
    } else {
      console.log('Failed write at document: ', error.documentRef);
      return false;
    }
  });
```

onWriteResult(successCallback)

Attaches a listener that is run every time a BulkWriter operation successfully completes.

Parameters:
Name Type Description
successCallback BulkWriter~successCallback

A callback to be called every time a BulkWriter operation successfully completes.

Example
```
let bulkWriter = firestore.bulkWriter();

bulkWriter
  .onWriteResult((documentRef, result) => {
    console.log(
      'Successfully executed write on document: ',
      documentRef,
      ' at: ',
      result
    );
  });
```

set(documentRef, data, optionsopt) → {Promise.<WriteResult>}

Write to the document referred to by the provided DocumentReference. If the document does not exist yet, it will be created. If you pass SetOptions., the provided data can be merged into the existing document.

Parameters:
Name Type Attributes Description
documentRef DocumentReference

A reference to the document to be set.

data T

The object to serialize as the document.

options SetOptions <optional>

An object to configure the set behavior.

Properties
Name Type Attributes Description
merge boolean <optional>

If true, set() merges the values specified in its data argument. Fields omitted from this set() call remain untouched. If your input sets any field to an empty map, all nested fields are overwritten.

mergeFields Array.<(string|FieldPath)> <optional>

If provided, set() only replaces the specified field paths. Any field path that is not specified is ignored and remains untouched. If your input sets any field to an empty map, all nested fields are overwritten.

Returns:
Type Description
Promise.<WriteResult>

A promise that resolves with the result of the write. If the write fails, the promise is rejected with a BulkWriterError.

Throws:

If the provided input is not a valid Firestore document.

Type
Error
Example
```
let bulkWriter = firestore.bulkWriter();
let documentRef = firestore.collection('col').doc();

bulkWriter
 .set(documentRef, {foo: 'bar'})
 .then(result => {
   console.log('Successfully executed write at: ', result);
 })
 .catch(err => {
   console.log('Write failed with: ', err);
 });
});
```

update(documentRef, dataOrField, …preconditionOrValues) → {Promise.<WriteResult>}

Update fields of the document referred to by the provided DocumentReference. If the document doesn't yet exist, the update fails and the entire batch will be rejected.

The update() method accepts either an object with field paths encoded as keys and field values encoded as values, or a variable number of arguments that alternate between field paths and field values. Nested fields can be updated by providing dot-separated field path strings or by providing FieldPath objects.

A Precondition restricting this update can be specified as the last argument.

Parameters:
Name Type Attributes Description
documentRef DocumentReference

A reference to the document to be updated.

dataOrField UpdateData | string | FieldPath

An object containing the fields and values with which to update the document or the path of the first field to update.

preconditionOrValues Precondition | * | string | FieldPath <repeatable>

An alternating list of field paths and values to update or a Precondition to restrict this update

Returns:
Type Description
Promise.<WriteResult>

A promise that resolves with the result of the write. If the write fails, the promise is rejected with a BulkWriterError.

Throws:

If the provided input is not valid Firestore data.

Type
Error
Example
```
let bulkWriter = firestore.bulkWriter();
let documentRef = firestore.doc('col/doc');

bulkWriter
 .update(documentRef, {foo: 'bar'})
 .then(result => {
   console.log('Successfully executed write at: ', result);
 })
 .catch(err => {
   console.log('Write failed with: ', err);
 });
});
```

Type Definitions

shouldRetryCallback(error) → {boolean}

Callback function set by BulkWriter#onWriteError that is run when a write fails in order to determine whether BulkWriter should retry the operation.

Parameters:
Name Type Description
error BulkWriterError

The error object with information about the operation and error.

Returns:
Type Description
boolean

Whether or not to retry the failed operation. Returning true retries the operation. Returning false will stop the retry loop.

successCallback(documentRef, result)

Callback function set by BulkWriter#onWriteResult that is run every time a BulkWriter operation successfully completes.

Parameters:
Name Type Description
documentRef DocumentReference

The document reference the operation was performed on

result WriteResult

The server write time of the operation.