Mustafa Şamdan
Mustafa Şamdan

Reputation: 11

Firebase - PHP - Error decoding message: cannot handle unknown field collection_Id on message

I am tring to read all documents from a collection and collectionGroup. Both of these requests i am getting an error. request for collection is as follows.

collection: users

data structure:

{
    email: "***@outlook.com.tr"
    id: 1252532
    image: "https://****.jpg"
    kimlik_id: 1252530
    middleName: null
    name: "***"
    role: 2
    role_id: 1252418
    shortName: "**"
    surname: "***"
    token: []
    url: "some-url"
}

PHP Code:

    $db = new FirestoreClient([
        'projectId' => '***',
        'keyFile' => '***',
        'keyFilePath' => '***'
    ]);

    $usersRef = $db->collection('users');
    $snapshot = $usersRef->documents();
    foreach ($snapshot as $user) {
        printf('User: %s' . PHP_EOL, $user->id());
        printf(PHP_EOL);
    }

Error:

In Serializer.php line 390:
cannot handle unknown field collection_Id on message google.firestore.v1.StructuredQuery.CollectionSelector

It works with Firebase Javascript library (for same firebase database and same collection).

JavaScript Code:

    firebase.initializeApp(firebaseConfig);
    db = firebase.firestore();

    var users = db.collection('users');
    users.get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(doc.id);
        });
    });

Upvotes: 1

Views: 185

Answers (2)

Nibrass H
Nibrass H

Reputation: 2487

Please use the Firestore Client Library and initialize it outside your function as following and mentioned in the PHP client library.

use Google\Cloud\Firestore\FirestoreClient;

function collection_ref($projectId)
{
   $db = new FirestoreClient( 'keyFilePath' => '/path/to/credentials.json','projectId' => 'my-project-id');

   $users = $db->collection('users');
   $snapshot = $users->documents();
   foreach ($snapshot as $document) {
      printf('Document' . PHP_EOL, $document->id());
    }
 }

With keyFilePath, Firestore library will search the Google Cloud Platform credentials using the string of the path.

Upvotes: 1

Methkal Khalawi
Methkal Khalawi

Reputation: 2477

I'm not sure from where $fb = new Firebase(); is coming. Anyway, this code should work:

use Google\Cloud\Firestore\FirestoreClient;

/**
 * Get a collection reference.
 * ```
 * collection_ref('your-project-id');
 * ```
 */
function collection_ref($projectId)
{
    // Create the Cloud Firestore client
    $db = new FirestoreClient([
        'projectId' => $projectId,
    ]);
    # [START fs_collection_ref]
    $collection = $db->collection('users');
    # [END fs_collection_ref]
    printf('Retrieved collection: %s' . PHP_EOL, $collection->name());
}

for more info check the following documentation

Upvotes: 0

Related Questions