简体   繁体   中英

How to get all documents in a collection from Firestore in React Native

I am trying to retrieve all documents from the 'users' collection in my firestore DB:

在此处输入图像描述

For now I'd just like to retrieve each userName and Role . I have seen a lost of similar questions but they always use snapshots like this:

async getMarkers() {
  const events = await firebase.firestore().collection('events').get()
    .then(querySnapshot => {
      querySnapshot.docs.map(doc => {
        console.log('LOG 1', doc.data());
        return doc.data();
      });
    });
  console.log('LOG 2', events);
  return events;
}

But I think my project structure is a bit different.

Here is my index.js located in the firebase folder:

Index.js

import * as firebase from 'firebase';
import 'firebase/firestore';

const firebaseConfig = {
    apiKey: "AIzaSyDVyMU4XZEaLmT17ksu2S6ndnypNwL555s",
    authDomain: "cyberpunkprojv1.firebaseapp.com",
    databaseURL: "https://cyberpunkprojv1.firebaseio.com",
    projectId: "cyberpunkprojv1",
    storageBucket: "cyberpunkprojv1.appspot.com",
    messagingSenderId: "837539155372",
    appId: "1:837539155372:web:e52a4bd30fd0c9da29be09",
    measurementId: "G-JGRZT5YX0Q"
};

export const init = () => {
    return firebase.initializeApp(firebaseConfig);
}


export const createUser = (user) =>
    firebase.firestore().collection('users').doc(user.userName).set(user); // I need to know how to create a subcollection when creating a document


export const getAllUsers = () => firebase.firestore().collection('users').get(); //This line does not work right now.

What I am primarily concerned with here is getAllUsers . Note though that createUser works exactly as intended.

This is in another.js screen in which getAllUsers is called:

CharacterViewScreen.js

   React.useEffect(()=>{
        console.log('Select Screen loaded.')
        userFetch();
      },[])

    const userFetch = async () => {
        try{
            await firebase.init();
    
            const users = await firebase.getAllUsers();
            console.log(users);
    
        } catch (error) {
            console.log(error);
        }
    }

The function runs correctly however this is what is logged in the console:

Console

Select Screen loaded.
t {
  "SP": null,
  "gP": t {
    "Je": Array [],
    "Ze": "F",
    "collectionGroup": null,
    "en": t {
      "Ye": "users|f:|ob:__name__asc,",
      "collectionGroup": null,
      "endAt": null,
      "filters": Array [],
      "limit": null,
      "orderBy": Array [
        t {
          "dir": t {
            "name": "asc",
          },
          "field": e {
            "len": 1,
            "offset": 0,
            "segments": Array [
              "__name__",
            ],
          },
          "wn": true,
        },
      ],
      "path": e {
        "len": 1,
        "offset": 0,
        "segments": Array [
          "users",
        ],
      },
      "startAt": null,
    },
    "endAt": null,
    "filters": Array [],
    "limit": null,
    "path": e {
      "len": 1,
      "offset": 0,
      "segments": Array [
        "users",
      ],
    },
    "startAt": null,
    "tn": Array [
      t {
        "dir": t {
          "name": "asc",
        },
        "field": e {
          "len": 1,
          "offset": 0,
          "segments": Array [
            "__name__",
          ],
        },
        "wn": true,
      },
    ],
  },
  "iP": undefined,
  "metadata": t {
    "fromCache": false,
    "hasPendingWrites": false,
  },
  "nP": t {
    "$E": t {
      "tl": [Function anonymous],
    },
    "BE": FirebaseAppImpl {
      "automaticDataCollectionEnabled_": false,
      "container": ComponentContainer {
        "name": "[DEFAULT]",
        "providers": Map {
          "app" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "app",
              "serviceProps": Object {},
              "type": "PUBLIC",
            },
            "container": [Circular],
            "instances": Map {
              "[DEFAULT]" => [Circular],
            },
            "instancesDeferred": Map {},
            "name": "app",
          },
          "platform-logger" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "platform-logger",
              "serviceProps": Object {},
              "type": "PRIVATE",
            },
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "platform-logger",
          },
          "fire-core-rn-version" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "fire-core-rn-version",
              "serviceProps": Object {},
              "type": "VERSION",
            },
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "fire-core-rn-version",
          },
          "fire-js-version" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "fire-js-version",
              "serviceProps": Object {},
              "type": "VERSION",
            },
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "fire-js-version",
          },
          "auth" => Provider {
            "component": Object {
              "instanceFactory": [Function instanceFactory],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "auth",
              "serviceProps": Object {
                "ActionCodeInfo": Object {
                  "Operation": Object {
                    "EMAIL_SIGNIN": "EMAIL_SIGNIN",
                    "PASSWORD_RESET": "PASSWORD_RESET",
                    "RECOVER_EMAIL": "RECOVER_EMAIL",
                    "VERIFY_EMAIL": "VERIFY_EMAIL",
                  },
                },
                "ActionCodeURL": [Function d],
                "Auth": [Function Lm],
                "AuthCredential": [Function kg],
                "EmailAuthProvider": [Function d],
                "Error": [Function M],
                "FacebookAuthProvider": [Function d],
                "GithubAuthProvider": [Function d],
                "GoogleAuthProvider": [Function d],
                "OAuthProvider": [Function d],
                "PhoneAuthProvider": [Function d],
                "RecaptchaVerifier": [Function d],
                "SAMLAuthProvider": [Function d],
                "TwitterAuthProvider": [Function d],
              },
              "type": "PUBLIC",
            },
            "container": [Circular],
            "instances": Map {
              "[DEFAULT]" => Object {
                "apiKey": "AIzaSyDVyMU4XZEaLmT17ksu2S6ndnypNwL555s",
                "appName": "[DEFAULT]",
                "authDomain": "cyberpunkprojv1.firebaseapp.com",
                "currentUser": null,
              },
            },
            "instancesDeferred": Map {},
            "name": "auth",
          },
          "auth-internal" => Provider {
            "component": Object {
              "instanceFactory": [Function instanceFactory],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "auth-internal",
              "type": "PRIVATE",
            },
            "container": [Circular],
            "instances": Map {
              "[DEFAULT]" => Object {
                "addAuthTokenListener": [Function bound ],
                "getToken": [Function bound ],
                "getUid": [Function bound ],
                "removeAuthTokenListener": [Function bound ],
              },
            },
            "instancesDeferred": Map {},
            "name": "auth-internal",
          },
          "fire-auth-version" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "fire-auth-version",
              "serviceProps": Object {},
              "type": "VERSION",
            },
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "fire-auth-version",
          },
          "database" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": true,
              "name": "database",
              "serviceProps": Object {
                "DataSnapshot": [Function DataSnapshot],
                "Database": [Function Database],
                "INTERNAL": Object {
                  "dataUpdateCount": [Function dataUpdateCount],
                  "forceLongPolling": [Function forceLongPolling],
                  "forceWebSockets": [Function forceWebSockets],
                  "interceptServerData": [Function interceptServerData],
                  "isWebSocketsAvailable": [Function isWebSocketsAvailable],
                  "setSecurityDebugCallback": [Function setSecurityDebugCallback],
                  "stats": [Function stats],
                  "statsIncrementCounter": [Function statsIncrementCounter],
                },
                "Query": [Function Query],
                "Reference": [Function Reference],
                "ServerValue": Object {
                  "TIMESTAMP": Object {
                    ".sv": "timestamp",
                  },
                },
                "TEST_ACCESS": Object {
                  "ConnectionTarget": [Function RepoInfo],
                  "DataConnection": [Function PersistentConnection],
                  "RealTimeConnection": [Function Connection],
                  "forceRestClient": [Function forceRestClient],
                  "hijackHash": [Function hijackHash],
                  "queryIdentifier": [Function queryIdentifier],
                },
                "enableLogging": [Function enableLogging],
              },
              "type": "PUBLIC",
            },
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "database",
          },
          "fire-rtdb-version" => Provider {
            "component": Component {
              "instanceFactory": [Function anonymous],
              "instantiationMode": "LAZY",
              "multipleInstances": false,
              "name": "fire-rtdb-version",
              "serviceProps": Object {},
              "type": "VERSION",
            },
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "fire-rtdb-version",
          },
          "storage" => Provider {
            "component": Component {
              "instanceFactory": [Function factory],
              "instantiationMode": "LAZY",
              "multipleInstances": true,
              "name": "storage",
            "container": [Circular],
            "instances": Map {},
            "instancesDeferred": Map {},
            "name": "fire-rtdb-version",
          },
          "storage" => Provider {
            "component": Component {
              "instanceFactory": [Function factory],
              "instantiationMode": "LAZY",
              "multipleInstances": true,
              "name": "storage",
              "serviceProps": Object {
                "Reference": [Function Reference],
                "Storage": [Function Service],
                "StringFormat": Object {
                  "BASE64": "base64",
                  "BASE64URL": "base64url",
                  "DATA_URL": "data_url",
                  "RAW": "raw",
                },
                "TaskEvent": Object {
                  "STATE_CHANGED": "state_changed",
                "TaskState": Object {
                  "CANCELED": "canceled",
                  "ERROR": "error",
                  "PAUSED": "paused",
                  "RUNNING": "running",
                  "SUCCESS": "s...(truncated to the first 10000 characters)

I feel like I have to be pretty close but I have no ides what that users object that is being logged actually is. Can I actually do this using this approach or do I have to use the snapshots like in the example? My method at least works a little bit because I created all of those database entries useing the createUser method in Index.js that is called a similar way in another view.

If I need to add any additional information please let me know.

The default string output of the QuerySnapshot object returned by Firestore is not going to be helpful to you. You should write code to check and iterate its results, using the provided API, as shown in the documentation :

const users = await firebase.getAllUsers();
// users is a QuerySnapshot
if (users.size() > 0) {
    users.forEach(doc => {
        console.log(doc.data())
    })
}
else {
    // decide what you want to do if no results
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM