Home > Software design >  Firestore database connection in a while loop
Firestore database connection in a while loop

Time:12-19

I have a problem with a connection to Firestore. Basically , in my web application, I want to get the documents from the database with documentId that start with the character I pass in input. In case they don't exist, I do a while loop where I randomly generate the characters and try to find the documents that start with that character:

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomCharacter = Math.floor(Math.random() * characters.length);
this.s = characters.charAt(randomCharacter);
console.log(this.s)


this.getItems(this.s, characters).then((data) => {
  this.items = data
  console.log(data)
  this.item0 = this.items[0]
  console.log(this.item0)
})


async getItems(randomCharPosition, characters) {
const itemRef = await firebase.firestore().collection("junction/"   this.itemId   "/reservations");
return itemRef.orderBy(firebase.firestore.FieldPath.documentId())
.startAt(randomCharPosition).endAt(randomCharPosition   "\uf8ff")
.get().then((querySnapshot) => {
  if (querySnapshot.size == 0) {
    console.log("First document not founded");
    var flag = false
    while (!flag) {
      console.log("No document founded");
      var randomCharacterPosition = Math.floor(Math.random() * characters.length);
      var newChar = characters.charAt(randomCharacterPosition)
      console.log(newChar)
      return itemRef.orderBy(firebase.firestore.FieldPath.documentId()).startAt(newChar).endAt(newChar   "\uf8ff")
        .get().then((data) => {
        if (data.size != 0) {
          console.log("SIZE > 0");
          flag = true
          return data.docs.map(doc => doc.data());
          }
          else console.log("REPEAT")
      })         
    }
  }
  else return querySnapshot.docs.map(doc => doc.data());
}
).catch((error) => {
  console.log("Error getting document:", error);
});

}

the problem is that the while loop is done only once after which it exits and returns undefined

enter image description here

What am I doing wrong in the getItems() function?

CodePudding user response:

You're calliing return itemRef.orderBy(... so that exits the while loop and the then function.

You can probably use await instead, to make the code wait instead:

var flag = false
while (!flag) {
  console.log("No document founded");
  var randomCharacterPosition = Math.floor(Math.random() * characters.length);
  var newChar = characters.charAt(randomCharacterPosition)
  const data = await itemRef.orderBy(firebase.firestore.FieldPath.documentId()).startAt(newChar).endAt(newChar   "\uf8ff").get()
  if (data.size != 0) {
    flag = true
    return data.docs.map(doc => doc.data()); //            
  • Related