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:
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.