簡體   English   中英

如何從 firebase 集合中獲取不等於給定 ID 的第一個文檔 ID?

[英]How can I get the first document ID from a firebase collection, which is not equal to a given ID?

我有'users'集合,其中包含每個用戶 ID 的文檔。 我還使用經過身份驗證的用戶 ID(匿名登錄)將當前用戶的 ID 存儲在userID變量中。

我需要根據最小值的計數器(此集合中的文檔數據項)獲取一個文檔 ID(不是文檔數據),並將其存儲在一個名為“receiverID”的變量中,但如果文檔 ID 等於當前用戶的ID,然后我想獲得下一個可用的 ID。

例如,如果我的平台上有 3 個用戶(A、B 和 C)並且存在以下“計數器”值:

  • A:1,B:2,C:3

理論上,當 A 查詢集合時,他們會得到自己的 doc ID。 然后我需要在“用戶”集合中獲取第二個文檔。

我從以下開始,但被卡住了:

receiverID = db.collection('users').orderBy('Questions Received','asc').limit(1)

此外,這是在事件偵聽器上觸發的(當用戶提交問題時),因此必須在 function 的下一部分之前解析“receiverID”。 這是我的事件監聽器的樣子:

const sayForm = document.querySelector('#say-form');
sayForm.addEventListener('submit', (e) => {
    e.preventDefault();

    db.collection('message').add({
        message: sayForm.sayInput.value,
        time: firebase.firestore.FieldValue.serverTimestamp(),
        sender: userID,
        currentReceiver: receiverID,
        received: 1
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    });
});

我能夠通過執行以下操作來解決它:

function getNextReceiver() {
  db.collection('users')
    .orderBy('Messages Received','asc')
    .limit(2)
    .get()
    .then(querySnapshot => {
      let x = querySnapshot.docs[0].id;
      let y = querySnapshot.docs[1].id;
      if (x == userID) {
        receiverID = y
      } else {
        receiverID = x;
      }
    });
    
}

getNextReceiver();

通過將搜索結果限制為 2 並將它們保存在一個變量中,我能夠與“userID”進行比較,並將“receiverID”相應地設置為不匹配的那個。

Firestore 中的查詢沒有不同的運算符,因此您必須獲取第一個文檔,如果它不是預期的 documentID,則獲取下一個文檔,依此類推。 您可以通過執行以下操作來做到這一點:

receiverID = this.getNextReceiver();

function getNextReceiver() {
    db.collection('users')
      .orderBy('Questions Received','asc')
      .limit(1)
      .get()
      .then(function (doc) {
          if(doc.id == userID){
              var validId = false;
              var tempDoc = doc;
              while(!validId){
                  db.collection('users')
                    .orderBy('Questions Received','asc')
                    .startAfter(tempDoc)
                    .limit(1)
                    .get()
                    .then(function (newDoc) {
                        if(newDoc.id != userID){
                            validId = true;
                            return newDoc.id;
                        }
                        tempDoc = newDoc;
                    });
                  
              }
          }
          return doc.id;
      });
}

所有這些都是同步運行的。 關於您的提交,不能保證會填充receiverID,因為它是由事件觸發的,因此您必須創建一個不填充該值的場景,或者在填充之前阻止用戶交互。

注意:所有這些代碼都未經測試,但對您來說應該是一個很好的起點。

暫無
暫無

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

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