首頁  >  文章  >  Java  >  如何從 Node.js 中的 Firebase 資料庫中選擇隨機產品?

如何從 Node.js 中的 Firebase 資料庫中選擇隨機產品?

Barbara Streisand
Barbara Streisand原創
2024-10-28 20:10:02141瀏覽

How to Select a Random Product from a Firebase Database in Node.js?

如何從Node.js 中的Firebase 資料庫檢索唯一的隨機產品:

在這種情況下,我們的目標是檢索單一,來自Firebase 資料庫中名為「products」的節點的隨機產品。這裡有兩種方法:

經典方法:

這涉及從「產品」節點檢索所有產品記錄並隨機選擇一個:

const rootRef = firebase.database().ref();
const productsRef = rootRef.child("products");

// Listen for a single snapshot of the products node
productsRef.once('value').then((snapshot) => {
  // Get all product names
  const productNames = [];
  snapshot.forEach((child) => {
    productNames.push(child.val().name);
  });

  // Select a random product name
  const randomProductName = productNames[Math.floor(Math.random() * productNames.length)];

  // Get the specific product data using the random name
  rootRef.child(`products/${randomProductName}`).once('value').then((product) => {
    console.log(product.val());
  });
});

非規範化方法:

在此技術中,我們建立一個名為「productIds」的單獨節點,其中僅包含所有產品的ID。這使我們能夠檢索隨機產品 ID,而無需獲取所有產品記錄:

const rootRef = firebase.database().ref();
const productIdsRef = rootRef.child("productIds");

// Listen for a single snapshot of the productIds node
productIdsRef.once('value').then((snapshot) => {
  // Get all product IDs
  const productIds = Object.keys(snapshot.val());

  // Select a random product ID
  const randomProductId = productIds[Math.floor(Math.random() * productIds.length)];

  // Get the specific product data using the random ID
  rootRef.child(`products/${randomProductId}`).once('value').then((product) => {
    console.log(product.val());
  });
});

以上是如何從 Node.js 中的 Firebase 資料庫中選擇隨機產品?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn