简体   繁体   English

如何从 React Native 中的 Firestore 获取集合中的所有文档

[英]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:我正在尝试从我的 firestore 数据库中的“用户”集合中检索所有文档:

在此处输入图像描述

For now I'd just like to retrieve each userName and Role .现在我只想检索每个userNameRole 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:这是位于 firebase 文件夹中的 index.js:

Index.js索引.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 .我在这里主要关心的是getAllUsers Note though that createUser works exactly as intended.请注意,尽管createUser完全按预期工作。

This is in another.js screen in which getAllUsers is called:这是在调用getAllUsers的 another.js 屏幕中:

CharacterViewScreen.js 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: function 运行正常,但是控制台中记录了以下内容:

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.我觉得我必须非常接近,但我不知道正在记录的用户 object 实际上是什么。 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.我的方法至少有点作用,因为我使用 Index.js 中的createUser方法创建了所有这些数据库条目,该方法在另一个视图中称为类似方法。

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. Firestore 返回的QuerySnapshot object 的默认字符串 output 对您没有帮助。 You should write code to check and iterate its results, using the provided API, as shown in the documentation :您应该使用提供的 API 编写代码来检查和迭代其结果,如文档中所示:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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