You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloud Firestore:如何按嵌套数据中的时间戳排序查询点赞数据?

How to Retrieve All Liked Data Sorted by Timestamp in Firestore

Hey there! Let's break this down step by step since you're new to Firestore—no worries, this is a common scenario once you get the hang of working with subcollections.

First, let's align on your data structure (I’ll go with the most logical interpretation from your description):

You have a top-level document called Liked, which contains a subcollection named chapter. Each document in the chapter subcollection represents a main chapter, and those chapter documents themselves have nested subcollections (let’s call them subchapters for clarity) where each document stores the actual likedAt timestamp of a user’s like.

If that’s accurate, here’s how you can pull all those liked entries sorted by timestamp:

1. Use a Collection Group Query

Since your liked timestamps are spread across multiple subcollections (one under each chapter document), you’ll need a collection group query to fetch all of them in one go. This query targets every subcollection with a specific name (in our case, subchapters) across your database.

Example Code (JavaScript)

import { collectionGroup, query, orderBy, getDocs } from "firebase/firestore";
import { db } from "./your-firebase-config-file";

async function getAllLikedEntriesSorted() {
  // Create a query targeting all "subchapters" subcollections, sorted by newest likes first
  const sortedQuery = query(
    collectionGroup(db, "subchapters"),
    orderBy("likedAt", "desc") // Swap to "asc" if you want oldest likes first
  );

  const querySnapshot = await getDocs(sortedQuery);
  
  // Convert the snapshot into a usable array of data
  const likedEntries = [];
  querySnapshot.forEach((doc) => {
    likedEntries.push({
      id: doc.id,
      parentChapterId: doc.ref.parent.parent.id, // Grab the parent chapter ID if needed
      ...doc.data()
    });
  });

  return likedEntries;
}

2. Fix the Required Index (If Needed)

When you run this query for the first time, Firestore will likely throw an error saying you need a composite index. Don’t stress—the error message includes a direct link to create the required index automatically. Just click it, confirm in the Firebase Console, and you’re set.

3. Adjust for a Slightly Different Structure

If your timestamps are stored directly in the chapter subcollection’s documents (instead of a nested subchapters subcollection), simplify the query to target just that single subcollection:

import { collection, query, orderBy, getDocs } from "firebase/firestore";
import { db } from "./your-firebase-config-file";

async function getAllLikedEntriesSorted() {
  // Target the "chapter" subcollection under the "Liked" document
  const chapterCollection = collection(db, "Liked", "chapter");
  const sortedQuery = query(chapterCollection, orderBy("likedAt", "desc"));

  const querySnapshot = await getDocs(sortedQuery);
  const likedEntries = [];
  
  querySnapshot.forEach((doc) => {
    likedEntries.push({ id: doc.id, ...doc.data() });
  });

  return likedEntries;
}

Quick Pro Tips

  • Stick to Firestore’s Timestamp type for your timestamp fields—avoid strings or Unix timestamps. This ensures accurate sorting and built-in date handling.
  • Add pagination if you have lots of liked entries. Use limit(10) to fetch a small subset, then startAfter(lastEntry.likedAt) to load the next page of results.

内容的提问来源于stack exchange,提问作者Subham Agarwala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:22:58