0

I want to access a document collection and get one random document that starts with a random chosen letter:

function generateWord() {

var wordsDb = database.ref('words');
var possibleChars = "abcdefghijklmnopqrstuvwyz";
var randomLetter = possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));

wordsDb.startAt(randomLetter).limitToFirst(1).once('value', (snapshot) => {
    console.log(snapshot.val());
    return snapshot.val();
  });
}

I use the function inside an exported function that is triggered when a document in another collection is created:

 var firstWord = generateWord();

            var game = {
                gameInfo: {
                    gameId: gameId,
                    playersIds: [context.params.playerId, secondPlayer.key],
                    wordSolution: firstWord,
                    round: 0
                },
                scores: {
                    [firstPlayerScore]: 0,
                    [secondPlayerScore]: 0
                },
            }

This is what the collection looks like:

enter image description here

I get the following warning in console log:

Function returned undefined, expected Promise or value

And also, console.log(snapshot.val()); shows that snapshot.val() is null.

Is my syntax wrong? I just want to get the value of the document.

2

1 Answer 1

1

Your code is executed before the data is received. Try to use async/await to wait for the data to return from firebase.

async function generateWord() {

var wordsDb = database.ref('words');
var possibleChars = "abcdefghijklmnopqrstuvwyz";
var randomLetter = possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));

var word = await wordsDb.startAt(randomLetter).limitToFirst(1).once('value') 
return word.val();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.