簡體   English   中英

如何從基於帶有 firestore 的字段的集合中獲取文檔?

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

我正在使用 Firestore 和 React,我有以下情況。
我有 2 個集合:訂單用戶
每個訂單都有一個名為userId的字段,基於該字段,我必須檢索users 集合中的用戶信息。
正如我所見,我有 2 個承諾:一個是獲取訂單,然后使用 for 循環,獲取 userId 並再次獲取用戶信息。
所以我必須結合 2 個對象。
在訂單對象中,我還需要用戶詳細信息

我試過這個,但它不起作用。

  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);
        
         
        });
      });
  }, []);

我們沒有關於它為什么不工作的任何信息......是否有任何錯誤或它只是沒有顯示任何內容。

無論如何,我在我的測試 Firestore 中創建了相同的結構,並直接在 nodejs 中使用了您的代碼(所有在 useEffect 中),但只發現了一個錯誤。 最后返回的是SyntaxError: Unexpected token . .

我已將其更正為:

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

現在代碼在控制台日志中返回值。 這可能是原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM