Reputation: 21721
I have a function for get the data from firestore db.
//...
async getHighestPlayers(game){
const snapshot = await this.db
.collection(game)
.orderBy("score","asc")
.limitToLast(1)
.get();
// What should I need to return ?
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
}
router.get('/', function(req, res, next) {
const highestPlayers = playerService.getHighestPlayers("game1");
res.render('index', { highestPlayers: highestPlayers});
});
How to make async getHighestPlayers(game)
return , so I can call and use to display it result?
Upvotes: 0
Views: 80
Reputation: 317477
You haven't really said what exactly the template needs to render. The template will receive whatever you send. If you're working with some spec to fulfill, you should covert the snapshot to whatever the client expects. We don't have that information.
In the absence of a specification, you could simply send the entire contents of the matching document (if one was even found):
async getHighestPlayers(game) {
const snapshot = this.db
.collection(game)
.orderBy("score","asc")
.limitToLast(1)
.get();
if (snapshot.docs.length > 0) {
return snapshot.docs[0].data();
}
else {
return undefined;
}
}
Then you will have to write some code to determine if there was actually a document present, and decide what you want to send if there was not:
router.get('/', function(req, res, next) {
const highestPlayers = playerService.getHighestPlayers("game1");
if (highestPlayers) {
res.render('index', { highestPlayers: highestPlayers});
}
else {
// what do you want to do if the document was missing?
}
});
Upvotes: 1
Reputation: 2281
you need to add async-await to wait for getHighestPlayers
to complete execution in index.js
router.get('/', async function(req, res, next) {
const highestPlayers = await playerService.getHighestPlayers("game1");
res.render('index', { highestPlayers: highestPlayers});
});
changes in getHighestPlayers
async getHighestPlayers(game){
const snapshot = await this.db
.collection(game)
.orderBy("score","asc")
.limitToLast(1)
.get();
return snapshot;
}
Upvotes: 1