A
A
Anastasia2021-11-18 17:20:39
firebase
Anastasia, 2021-11-18 17:20:39

How to get random document from firebase collection?

Hello. I have a page where all elements from firebase are displayed:

<div class="doggo" v-for="dog in doggo" :key="dog.id">
    <h2>{{ dog.name }}</h2>
    <var-image :src="dog.photo" />
    <p>{{ dog.desc }}</p>
</div>


And the script itself, where I get all the necessary data from firebase:

firebase.initializeApp(config);
const db = firebase.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
const doggoCollection = db.collection("doggo");

export {
  db,
  auth,
  storage,
  doggoCollection,
};


import { doggoCollection, storage } from "@/firebase";

export default {
  data() {
    return {
      doggo: [],
    };
  },
  methods: {
    async getDogs() {
      try {
        const querySnapshot = await doggoCollection.get();
        querySnapshot.forEach(async (doc) => {
          console.log(doc.data());
          let img = "";
          if (doc.data().photo) {
            img = await storage.ref().child(doc.data().photo).getDownloadURL();
          }
          this.doggo.push({
            id: doc.id,
            name: doc.data().name,
            desc: doc.data().desc,
            photo: img,
            img: doc.data().photo,
          });
          console.log("get doggo", this.doggo);
        });

        console.log(this.doggo);
      } catch (e) {
        console.log(e);
      }
    },
  },
  async mounted() {
    await this.getDogs();
  },
};


When loading the page, I want to get only one random value from the collection. I didn't find anything in the firebase documentation that could help me.
Perhaps you will have some ideas?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question