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:
- Mishandling the QuerySnapshot: When you call
db.collection('/preferences').get(), you get aQuerySnapshot(which represents all documents in the collection), not a singleDocumentSnapshot. Checkingdoc.existsand callingdoc.data()on this snapshot is incorrect—those methods are for individual documents, not collections of documents. - Wrong initial type: You initialized
engineersas 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 toasync/awaitfor 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:
engineersstarts 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
preferencesFirestore 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
相关产品推荐
相关产品推荐

