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

如何在Firebase中获取嵌套子节点的商品ID、名称、数量等值?

Hey there! Looking at your Firebase Realtime Database structure from the screenshot, I can see you're trying to extract specific values like product_id, product_name, and quantity from the nested products nodes under each order. Let's walk through how to do this across different platforms with clear code examples.

First, let's recap your data structure for clarity (based on the screenshot):

orders
  |- [unique_order_id]
      |- products
          |- [unique_product_entry_id]
              |- product_id: "your_product_id"
              |- product_name: "Product Name"
              |- quantity: 3
              |- ... (other product fields)

1. Firebase Web SDK (JavaScript)

Use the onValue listener to fetch and iterate through the nested data:

import { getDatabase, ref, onValue } from "firebase/database";

// Initialize database reference
const db = getDatabase();
const ordersRef = ref(db, 'orders');

// Listen for changes or fetch one-time data
onValue(ordersRef, (snapshot) => {
  const ordersData = snapshot.val();
  
  if (!ordersData) {
    console.log("No orders found in the database.");
    return;
  }

  // Loop through each order
  Object.keys(ordersData).forEach(orderId => {
    const order = ordersData[orderId];
    
    // Check if the order has a products node
    if (order.products) {
      // Loop through each product in the order
      Object.keys(order.products).forEach(productKey => {
        const product = order.products[productKey];
        
        // Extract the values you need
        const productId = product.product_id;
        const productName = product.product_name;
        const quantity = product.quantity;
        
        // Do something with these values (log, render, store, etc.)
        console.log(`Product ID: ${productId}, Name: ${productName}, Quantity: ${quantity}`);
      });
    }
  });
}, (error) => {
  console.error("Error fetching data:", error);
});

2. Android (Kotlin)

Use a ValueEventListener to traverse the nested nodes:

import com.google.firebase.database.*

// Initialize database reference
val database = FirebaseDatabase.getInstance()
val ordersRef = database.getReference("orders")

ordersRef.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(snapshot: DataSnapshot) {
        // Iterate through all orders
        for (orderSnapshot in snapshot.children) {
            // Access the products node of the current order
            val productsSnapshot = orderSnapshot.child("products")
            
            // Iterate through each product entry
            for (productSnapshot in productsSnapshot.children) {
                // Extract values directly from the snapshot
                val productId = productSnapshot.child("product_id").getValue(String::class.java)
                val productName = productSnapshot.child("product_name").getValue(String::class.java)
                val quantity = productSnapshot.child("quantity").getValue(Int::class.java)
                
                // Use the extracted values (example: log them)
                productId?.let {
                    Log.d("FirebaseData", "Product ID: $it | Name: ${productName ?: "Unnamed"} | Quantity: ${quantity ?: 0}")
                }
            }
        }
    }

    override fun onCancelled(error: DatabaseError) {
        Log.w("FirebaseData", "Failed to read data.", error.toException())
    }
})

3. iOS (Swift)

Use Firebase's observe method to parse the nested data:

import FirebaseDatabase

// Initialize database reference
let ordersRef = Database.database().reference().child("orders")

ordersRef.observe(.value) { snapshot in
    guard let ordersDict = snapshot.value as? [String: [String: Any]] else {
        print("No orders found or invalid data format.")
        return
    }
    
    // Loop through each order
    for (_, order) in ordersDict {
        // Check if the order contains a products dictionary
        guard let products = order["products"] as? [String: [String: Any]] else { continue }
        
        // Loop through each product entry
        for (_, product) in products {
            // Extract the required values
            guard let productId = product["product_id"] as? String,
                  let productName = product["product_name"] as? String,
                  let quantity = product["quantity"] as? Int else { continue }
            
            // Use the values (example: print them)
            print("Product ID: \(productId) | Name: \(productName) | Quantity: \(quantity)")
        }
    }
} withCancel: { error in
    print("Error fetching data: \(error.localizedDescription)")
}

Quick Tips

  • If you only need data from a specific order, target its products node directly (e.g., ref(db, "orders/your_order_id/products")) to avoid iterating all orders.
  • Ensure your Firebase Realtime Database rules grant read access to the orders path (otherwise you'll get permission denied errors).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:58:36