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

Firebase时间范围查询问题求助:Node.js下获取数组内指定时间戳范围数据返回空值

Troubleshooting Your Firebase Firestore Time Range Query

Let’s break down the issues in your code and walk through the fixes to get your time range query working correctly:

Key Issues in Your Current Code

1. You’re Not Collecting Query Results Properly

Your use of document.forEach(doc => { doc.data() }) inside res.json() doesn’t actually return any data—forEach only iterates over documents, it doesn’t collect or return their content. This means you’re sending an empty/undefined response even if the query finds matching documents.

2. Potential Timestamp Type Mismatch

If your timestamp field in Firestore is stored as a Firestore Timestamp object (not a raw numeric Unix timestamp), comparing it with millisecond values directly won’t work. Firestore requires matching data types for range queries.

Corrected Implementation

Here’s the fixed code with explanations for each change:

import { Timestamp } from "firebase/firestore"; // Import Timestamp if needed

export const getLastWeekDataFromDatabase = async (req: IdRequest, res: Response) => { 
  const deviceId = req.params.deviceId;
  try { 
    // Define your time range in milliseconds
    const startTimeMs = 1660483660946;
    const endTimeMs = 1660483712221;

    const historyRef = db.collection("AQData")
      .doc(deviceId)
      .collection("history");

    // Convert ms timestamps to Firestore Timestamp objects (use if your field is a Timestamp type)
    // If your timestamp is stored as a number, skip this and use startTimeMs/endTimeMs directly
    const startTimestamp = Timestamp.fromMillis(startTimeMs);
    const endTimestamp = Timestamp.fromMillis(endTimeMs);

    const querySnapshot = await historyRef
      .orderBy("timestamp")
      .startAt(startTimestamp) // Use startTimestamp or startTimeMs based on your field type
      .endAt(endTimestamp)     // Same here
      .get();

    // Map documents to their data (this collects the results into an array)
    const results = querySnapshot.docs.map(doc => ({
      id: doc.id, // Include document ID if you need it
      ...doc.data()
    }));

    // Handle empty result case clearly
    if (results.length === 0) {
      return res.status(404).json({ message: "No data found in the specified time range" });
    }

    res.status(200).json(results); 
  } catch(error) { 
    console.error("Fetch error:", error); // Log error for debugging
    res.status(500).json({ error: "Failed to retrieve data", details: error.message }); 
  }; 
};

Critical Fixes Explained

  • Result Collection: Used querySnapshot.docs.map() to create an array of document data. This ensures you’re actually sending the retrieved data back in the response.
  • Timestamp Alignment: Added conversion to Firestore Timestamp objects (adjust based on how your timestamp field is stored in Firestore—use raw ms values if your field is a number).
  • Error & Empty Result Handling: Added clear logging for debugging, and a 404 response when no data matches the query to avoid confusing empty responses.

Additional Debugging Steps

  1. Check Field Type: Go to your Firestore console and verify if the timestamp field in the history collection is a Timestamp or Number. Ensure your query uses the same type.
  2. Test Query in Console: Use Firestore’s built-in query builder to run the same time range query manually. If it returns results, the issue is in your code’s timestamp handling or result collection.
  3. Log Snapshot Size: Add console.log("Matching docs:", querySnapshot.size) after fetching the snapshot to confirm if the query is finding any documents.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:07:46