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

Node.js中如何将Firestore的preferences集合转为指定格式数组?

解决Firestore集合转指定数组结构的问题

Hey there! Let's figure out why your code isn't working and fix it up to get that engineers array you need.

核心问题分析

Your current code has two key issues that are preventing you from getting the target array:

  1. Mishandling the QuerySnapshot: When you call db.collection('/preferences').get(), you get a QuerySnapshot (which represents all documents in the collection), not a single DocumentSnapshot. Checking doc.exists and calling doc.data() on this snapshot is incorrect—those methods are for individual documents, not collections of documents.
  2. Wrong initial type: You initialized engineers as an object {}, but your target is an array [].

Fixed Code

Here's the revised version of your getPreferancesArray function that will correctly build the engineers array:

// enginer.js file
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.getPreferancesArray = async (req, res) => {
  try {
    // Initialize engineers as an empty array (matches your target structure)
    let engineers = [];
    // Fetch all documents from the preferences collection
    const querySnapshot = await db.collection('preferences').get();
    
    // Loop through each document and add its data to the array
    querySnapshot.forEach(doc => {
      // doc.data() returns the fields of the document as an object—exactly what we need for the array items
      engineers.push(doc.data());
    });

    // Handle empty collection case (optional but helpful)
    if (engineers.length === 0) {
      return res.json({ 
        message: "No preference documents found in Firestore", 
        engineers: [] 
      });
    }

    // Send the completed array back as response
    res.json(engineers);
  } catch (error) {
    // Catch and handle any errors during the database call
    console.error('Error fetching preferences:', error);
    res.status(500).json({ error: 'Failed to load engineer preferences' });
  }
};

Key Changes Explained

  • Async/Await: Switched from .then() chains to async/await for cleaner, more readable code (you can still use Promises if you prefer, but async/await is easier to follow).
  • Correct QuerySnapshot Handling: We use querySnapshot.forEach() to iterate over every document in the collection, pushing each document's data (as an object) into the engineers array.
  • Array Initialization: engineers starts as an empty array instead of an object, so it matches your target structure from the start.
  • Error Handling: Added a try/catch block to handle database errors gracefully, so your API doesn't hang or return an unclear response when something goes wrong.
  • Empty Collection Check: Optional but useful to let the client know if there are no documents in the preferences collection.

Extra Notes

  • Make sure each document in your preferences Firestore collection has exactly the structure you want for the array items (e.g., { html: 5, angular: 5, ... }). If documents have extra fields you don't need, you can filter them out when pushing to the array:
    // Example: Exclude a "documentId" field if present
    const { documentId, ...preferenceData } = doc.data();
    engineers.push(preferenceData);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:05:20