node.js - loop through documents in a collection to get fields
问题描述
I have a collection called users in firebase firestore. Each document in the collection users is a user registered in the app. Each document has a field called token_ids. How can I loop through all the documents to get the values in the token_ids field. I am using firebase cloud functions to do so. Here is the code snippet I tried using but it did not work:
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp();
//fetch all token ids of users
const tokenReference = admin.firestore().collection("users");
const tokenSnapshot = await tokenReference.get();
tokenSnapshot.forEach((doc) =>{
console.log("Token ids are:" + doc.data().token_id);
});
});
解决方案
Took me a while but finally found the solution to it. Here it is. It is the first solution given by Dhruv Shah but slightly modified :
async function fetchAllTTokenIds() {
const tokenReference = admin.firestore().collection("users");
const tokenSnapshot = await tokenReference.get();
const results = [];
tokenSnapshot.forEach(doc => {
results.push(doc.data().token_id);
});
const tokenIds = await Promise.all(results);
return console.log("Here =>" +tokenIds);
}
推荐阅读
- java - E/UncaughtException: android.content.res.Resources$NotFoundException: 资源 ID #0x7f0800a8
- node.js - nodejs在天蓝色的活动目录中找到用户
- python - 打印所有文本,只需要一个
- javascript - 从 windows.showModalDialog 迁移到 window.open
- laravel - Twilio 消息 - 我无法访问数据属性
- javascript - 单击复选框时显示/隐藏 Gridview 控件 - Javascript
- python - 在保存时添加 ManyToMany 字段
- r - file.info R-package 中没有 uname 和 gname
- c# - 值为 DBNull.Value 的 C# MySqlCommand 参数不起作用
- c++ - 这个模板定义在 C++ 中是什么意思?