简体   繁体   中英

How to get document from a collection based on a field with firestore?

I am using Firestore and React and I have the following situation.
I have 2 collections : orders and users .
Every order has a field called userId and based on that I have to retrieve the user information that is inside users collection .
As I saw I have 2 promises : one to get the orders and then use a for loop, get the userId and get again the user info.
So I have to combine 2 object.
Inside the order object I need also the user details

I tried this but it doesn't work.

  useEffect(() => {
    firestore()
      .collection(`orders`)
      .get()
      .then(result => {
        let data = result.docs.map(function(p) {
          return firestore()
            .collection(`users`)
            .doc(p.data().orderId)
            .get()
            .then(function(user) {
    
             
              return {id: user.id,  user.data()};
            });
        });
        Promise.all(data).then(function(values) {
          
          console.log(values);
        
         
        });
      });
  }, []);

We do not have any information about why it's not working... is there any error or it just not show anything.

Anyway, I have created the same structure in my testing Firestore and used your code (all that is inside useEffect) in nodejs directly and found only one error. In last return there is SyntaxError: Unexpected token . .

I have corrected it to:

return {id: user.id,  data: user.data()};

And now the code is returning values in console log. This might be the reason.

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