Heim  >  Artikel  >  Java  >  Wie wähle ich ein zufälliges Produkt aus einer Firebase-Datenbank in Node.js aus?

Wie wähle ich ein zufälliges Produkt aus einer Firebase-Datenbank in Node.js aus?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 20:10:02141Durchsuche

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

So rufen Sie ein einzigartiges Zufallsprodukt aus einer Firebase-Datenbank in Node.js ab:

In diesem Zusammenhang wollen wir ein einzelnes abrufen , zufälliges Produkt von einem Knoten namens „products“ in einer Firebase-Datenbank. Hier sind zwei Ansätze:

Klassischer Ansatz:

Dabei werden alle Produktdatensätze aus dem Knoten „Produkte“ abgerufen und ein zufälliger Datensatz ausgewählt:

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());
  });
});

Denormalisierter Ansatz:

Bei dieser Technik erstellen wir einen separaten Knoten namens „productIds“, der nur die IDs aller Produkte enthält. Dadurch können wir eine zufällige Produkt-ID abrufen, ohne alle Produktdatensätze abzurufen:

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());
  });
});

Das obige ist der detaillierte Inhalt vonWie wähle ich ein zufälliges Produkt aus einer Firebase-Datenbank in Node.js aus?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn