簡體   English   中英

Firebase 如何在 js 上按孩子排序

[英]Firebase how to Order by child on js

有時間戳的消息點不上,試了很多方法還是不行,求幫忙圖片等數據的整理

代碼數據庫

數據:

  { chatRoom : {
      "232": {
        "-NKHmBkCihoyRiYABX5O": {
          "createdAtDate": "2022-12-27",
          "createdAtTime": "17:52:49",
          "fromType": 4,
          "message": "message2",
          "readByAdmin": false,
          "readByUser": true,
          "timestamp": 1672131169.174558,
          "user": "tuan do",
          "userId": "232"
        }
      },
      "242": {
        "-NKHm6svnBJhWq321aNv": {
          "createdAtDate": "2022-12-27",
          "createdAtTime": "17:52:29",
          "fromType": 3,
          "message": "message1",
          "readByAdmin": false,
          "readByUser": true,
          "timestamp": 1672131149.252743,
          "user": "solashi 歯科衛生士",
          "userId": "242"
        }
      }
    }
}

代碼:const dbRefAdmin = firebase.database().ref('chatRoom').orderByChild('timestamp').limitToLast(10)

要排列 Firebase 中的圖片等數據,您可以使用 orderByChild() 方法指定要用於對數據進行排序的子鍵。 然后,您可以使用 startAt()、endAt() 和 equalTo() 方法根據子項的值過濾查詢結果。

下面是一個如何使用 orderByChild() 排列圖片等數據的示例:

// Get a reference to the database
var database = firebase.database();

// Get a reference to the 'pictures' child of the database
var picturesRef = database.ref("pictures");

// Create a query to order the pictures by their title
var query = picturesRef.orderByChild("title");

// Execute the query and process the results
query.once("value").then(function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var key = childSnapshot.key;
    var childData = childSnapshot.val();
    console.log("key: " + key + ", title: " + childData.title);
  });
});

在此示例中,查詢 object 按標題對數據庫的圖片子項中的圖片進行排序。 once("value") 方法用於執行查詢並將結果作為快照獲取。 快照包含與查詢匹配的子項列表,forEach() 方法用於遍歷列表並處理結果。

您還可以使用 startAt()、endAt() 和 equalTo() 方法根據 title child 的值過濾查詢結果。 例如,您可以使用以下代碼獲取標題以字母“A”開頭的所有圖片:

var query = picturesRef.orderByChild("title").startAt("A");

或者你可以使用下面的代碼獲取標題為“Sunset”的所有圖片:

var query = picturesRef.orderByChild("標題").equalTo("日落");

我希望這有幫助。 如果您有任何問題,請告訴我。

一個簡單的答案:

  • 嘗試使用“ orderBy ”而不是“orderByChild
  • 然后是“ limit ”而不是“ limitToLast

如果下面的代碼解決了您的問題,請在評論中提供反饋並將您的帖子置於已解決狀態。

官方文檔: 使用 Cloud Firestore 訂購和限制數據

 var is_start_load = true; const dbRefAdmin = firebase.database().ref('chatRoom').orderBy('timestamp').limit(10);

暫無
暫無

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

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