Coach
Coach

Reputation: 521

Firestore: Key writes does not exist in the provided array

Can anyone tell me, what the following error message tries to tell me?

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Key writes does not exist in the provided array.' in /vendor/google/cloud/Core/src/ArrayTrait.php:38

Stack trace: 
    #0 /vendor/google/cloud/Firestore/src/Connection/Grpc.php(127): Google\Cloud\Firestore\Connection\Grpc->pluck('writes', Array) 
    #1 /vendor/google/cloud/Firestore/src/WriteBatch.php(381): Google\Cloud\Firestore\Connection\Grpc->commit(Array) 
    #2 import.php(45): Google\Cloud\Firestore\WriteBatch->commit() 
    #3 {main} thrown in /vendor/google/cloud/Core/src/ArrayTrait.php on line 38

my code looks like:

$batch = $project->db->batch();
foreach($memberList as $member){
    $addedDocRef = $collection->newDocument();
    $data["id"] = $addedDocRef->id();
    $data["creation"] = $this->generateCreation();
    $data["publication"] = $this->generatePublication();    
    $batch->create($addedDocRef, $data);
}
$batch->commit();

Upvotes: 7

Views: 779

Answers (2)

smartilabs
smartilabs

Reputation: 121

Answer from Alexander is correct for specific situation.

More generic solution is to use function provided directly within Firestore, that checks if anything was enqueued to batch.

if (!$batch->isEmpty()) {
    $batch->commit();
}

Source: https://github.com/googleapis/google-cloud-php-firestore/blob/master/src/WriteBatch.php#L483

Upvotes: 3

Alexander Znaydyuk
Alexander Znaydyuk

Reputation: 98

It tells you that you are running a commit, but batch contains no operations. Probably when your $memberList is empty this error shows up. An easy way to prevent the error is:

if (! empty($memberList)) {
    $batch->commit();
}

Also, are you sure that $batch->create() exists? You should use set() method. Here is latest firestore doc:

$batch = $db->batch();

# Set the data for NYC
$nycRef = $db->collection('cities')->document('NYC');
$batch->set($nycRef, [
    'name' => 'New York City'
]);

# Update the population for SF
$sfRef = $db->collection('cities')->document('SF');
$batch->update($sfRef, [
    ['path' => 'population', 'value' => 1000000]
]);

# Delete LA
$laRef = $db->collection('cities')->document('LA');
$batch->delete($laRef);

# Commit the batch
$batch->commit();

Upvotes: 4

Related Questions