[javascript] Getting all documents from one collection in Firestore

Hi I'm starting with javascript and react-native and I'm trying to figure out this problem for hours now. Can someone explain me how to get all the documents from firestore collection ?

I have been trying 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;
}

Log 1 prints all the objects(one by one) but log 2 is undefined, why ?

The answer is


The example in the other answer is unnecessarily complex. This would be more straightforward, if all you want to do is return the raw data objects for each document in a query or collection:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    return snapshot.docs.map(doc => doc.data());
}

if you want include Id

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = querySnapshot.docs.map((doc) => {
        return { id: doc.id, ...doc.data() }
      })
      console.log(tempDoc)
    })
}

Same way with array

async getMarkers() {
  const events = await firebase.firestore().collection('events')
  events.get().then((querySnapshot) => {
      const tempDoc = []
      querySnapshot.forEach((doc) => {
         tempDoc.push({ id: doc.id, ...doc.data() })
      })
      console.log(tempDoc)
   })
 }

if you need to include the key of the document in the response, another alternative is:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    const documents = [];
    snapshot.forEach(doc => {
       documents[doc.id] = doc.data();
    });
    return documents;
}

I made it work this way:

async getMarkers() {
  const markers = [];
  await firebase.firestore().collection('events').get()
    .then(querySnapshot => {
      querySnapshot.docs.forEach(doc => {
      markers.push(doc.data());
    });
  });
  return markers;
}

You could get the whole collection as an object, rather than array like this:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    const collection = {};
    snapshot.forEach(doc => {
        collection[doc.id] = doc.data();
    });
    return collection;
}

That would give you a better representation of what's in firestore. Nothing wrong with an array, just another option.


I prefer to hide all code complexity in my services... so, I generally use something like this:

In my events.service.ts

    async getEvents() {
        const snapchot = await this.db.collection('events').ref.get();
        return new Promise <Event[]> (resolve => {
            const v = snapchot.docs.map(x => {
                const obj = x.data();
                obj.id = x.id;
                return obj as Event;
            });
            resolve(v);
        });
    }

In my sth.page.ts

   myList: Event[];

   construct(private service: EventsService){}

   async ngOnInit() {
      this.myList = await this.service.getEvents();
   }

Enjoy :)


Here's a simple version of the top answer, but going into an object with the document ids:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    return snapshot.docs.reduce(function (acc, doc, i) {
              acc[doc.id] = doc.data();
              return acc;
            }, {});
}

Try following LOCs

    let query = firestore.collection('events');
    let response = [];
    await query.get().then(querySnapshot => {
          let docs = querySnapshot.docs;
          for (let doc of docs) {
              const selectedEvent = {
                     id: doc.id,
                     item: doc.data().event
                  };
             response.push(selectedEvent);
          }
   return response;

Two years late but I just began reading the Firestore documentation recently cover to cover for fun and found withConverter which I saw wasn't posted in any of the above answers. Thus:

If you want to include ids and also use withConverter (Firestore's version of ORMs, like ActiveRecord for Ruby on Rails, Entity Framework for .NET, etc), then this might be useful for you:

Somewhere in your project, you probably have your Event model properly defined. For example, something like:

Your model (in TypeScript): ./models/Event.js

export class Event {
  constructor (
    public id: string,
    public title: string,
    public datetime: Date
  )
}

export const eventConverter = {
  toFirestore: function (event: Event) {
    return {
      // id: event.id,  // Note! Not in ".data()" of the model!
      title: event.title,
      datetime: event.datetime
    }
  },
  fromFirestore: function (snapshot: any, options: any) {
    const data = snapshot.data(options)
    const id = snapshot.id
    return new Event(id, data.title, data.datetime)
  }
}

And then your client-side TypeScript code:

import { eventConverter } from './models/Event.js'

...

async function loadEvents () {
  const qs = await firebase.firestore().collection('events')
    .orderBy('datetime').limit(3)  // Remember to limit return sizes!
    .withConverter(eventConverter).get()

  const events = qs.docs.map((doc: any) => doc.data())

  ...
}

Two interesting quirks of Firestore to notice (or at least, I thought were interesting):

  1. Your event.id is actually stored "one-level-up" in snapshot.id and not snapshot.data().

  2. If you're using TypeScript, the TS linter (or whatever it's called) sadly isn't smart enough to understand:

const events = qs.docs.map((doc: Event) => doc.data())

even though right above it you explicitly stated: .withConverter(eventConverter)

Which is why it needs to be doc: any.

(But! You will actually get Array<Event> back! (Not Array<Map> back.) That's the entire point of withConverter... That way if you have any object methods (not shown here in this example), you can immediately use them.)

It makes sense to me but I guess I've gotten so greedy/spoiled that I just kinda expect my VS Code, ESLint, and the TS Watcher to literally do everything for me. Oh well.


Formal docs (about withConverter and more) here: https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects


Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with firebase tag:

How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore FirebaseInstanceIdService is deprecated Failed to resolve: com.google.firebase:firebase-core:16.0.1 NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count iOS Swift - Get the Current Local Time and Date Timestamp Error: fix the version conflict (google-services plugin) Enabling CORS in Cloud Functions for Firebase Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() Plugin with id 'com.google.gms.google-services' not found Didn't find class "com.google.firebase.provider.FirebaseInitProvider"? How to use Apple's new .p8 certificate for APNs in firebase console Convert Promise to Observable How to add SHA-1 to android application how to end ng serve or firebase serve How do you send a Firebase Notification to all devices via CURL? Class file for com.google.android.gms.internal.zzaja not found No notification sound when sending notification from firebase in android How do I detect if a user is already logged in Firebase? FCM getting MismatchSenderId Firebase (FCM) how to get token How to handle notification when app in background in Firebase What is FCM token in Firebase? Is it safe to expose Firebase apiKey to the public? Firebase Permission Denied How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Firebase onMessageReceived not called when app in background Firebase cloud messaging notification not received by device Where can I find the API KEY for Firebase Cloud Messaging? How to get a list of all files in Cloud Storage in a Firebase app? Notification Icon with the new Firebase Cloud Messaging system Unable to get provider com.google.firebase.provider.FirebaseInitProvider Failed to resolve: com.google.firebase:firebase-core:9.0.0 Firebase TIMESTAMP to date and Time how to get all child list from Firebase android Android Firebase, simply get one child object's data MongoDB vs Firebase Firebase: how to generate a unique numeric ID for key? Query based on multiple where clauses in Firebase How to delete/remove nodes on Firebase In Firebase, is there a way to get the number of children of a node without loading all the node data? Firebase Storage How to store and Retrieve images

Questions with react-native tag:

How to resolve the error on 'react-native start' React Native Error: ENOSPC: System limit for number of file watchers reached How to update core-js to core-js@3 dependency? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 How can I force component to re-render with hooks in React? What is useState() in React? Getting all documents from one collection in Firestore ReactJS: Maximum update depth exceeded error React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH React Native version mismatch How to use ImageBackground to set background image for screen in react-native How to clear react-native cache? npm install Error: rollbackFailedOptional Hide header in stack navigator React navigation Unable to load script from assets index.android.bundle on windows What are my options for storing data when using React Native? (iOS and Android) React navigation goBack() and update parent state if-else statement inside jsx: ReactJS Open Url in default web browser Module AppRegistry is not registered callable module (calling runApplication) React-Native Button style not work React native ERROR Packager can't listen on port 8081 How to re-render flatlist? Draw horizontal rule in React Native Disable back button in react navigation What is the meaning of 'No bundle URL present' in react-native? How to loop and render elements in React-native? How can I regenerate ios folder in React Native project? Could not connect to React Native development server on Android How to use zIndex in react-native Package signatures do not match the previously installed version Using Axios GET with Authorization Header in React-Native App How to set shadows in React Native for android? Does 'position: absolute' conflict with Flexbox? Unable to Resolve Module in React Native App Axios get in url works but with second parameter as object it doesn't How can I put an icon inside a TextInput in React Native? How do I add an element to array in reducer of React native redux? Unable to connect with remote debugger error: package com.android.annotations does not exist "React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View> Error Running React Native App From Terminal (iOS) How to set image width to be 100% and height to be auto in react native? NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app React Native: Possible unhandled promise rejection How to show SVG file on React Native? how to delete installed library form react native project Run react-native on android emulator

Questions with google-cloud-firestore tag:

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count