Mapping data from two Firestore collections with js [duplicate]

女生的网名这么多〃 提交于 2020-12-15 04:56:13

问题


I have two collections namely:CURRENCY-PAIR and Alerts.

The CURRENCY-PAIR collection contains the following;

  • Currency-Pair Name
  • Currency-AskPrice
  • Currency-BidPrice

The Alerts collection contains the following:

  • Alert_id

  • Alert_Status

How can i map the Currency-Pair Name from the CURRENCY-PAIR collection and Alert_Status from the Alerts collection to a list showing both.


回答1:


Say you want to fetch a collection of data from firestore, you should first get the reference of the collection:

const currencyRef = firestore().collection('CURRENCY-PAIR');
const alertRef = firestore().collection('Alert_Status');

You could then use these references to get the data from firestore:

currencyRef.get()
  .then((doc) => {
    console.log(doc.data());
  });

As you can see, the data is in the form of a promise, which you have to resolve. The doc.data() is an array of all the data in your collection, in the form of JS objects.

Since the data comes as a promise, you can create an async fetch function, which resolves the promise, and puts the data in a new array which gets returned. Maybe you can do something like this:

const fetchAllCurrencies = async () => {
  const obj = []; // empty array to put collections in
  const currencyRef = firestore().collection('CURRENCY-PAIR'); // ref
  const snapshot = await currencyRef.get() // resolve promise from firestore
  snapshot.forEach((doc) => { // loop over data
    obj.push({ id: doc.id, ...doc.data() }); // push each collection to array
  });
  return obj; // return array with collection objects 
}

You may create a similar function for the alert collection.

I'm not entirely sure about what you mean with: 'How can i map the Currency-Pair Name from the CURRENCY-PAIR collection and Alert_Status from the Alerts collection to a list showing both.'

by creating functions like the one above, you can get arrays of collection js objects. You can combine two arrays with:

const newArray = array1.concat(array2);

This will melt two arrays into one. It's probably not what you want to do. If I were you, I'd keep the two arrays separate.



来源:https://stackoverflow.com/questions/64943348/mapping-data-from-two-firestore-collections-with-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!