我正在尝试获取数据库中所有用户的文档ID。 为此,我编写了以下代码:
exports.scheduledFunction = functions.pubsub
.schedule('every 2 minutes')
.onRun(async context => {
console.log('This will be run every 2 minutes!');
try {
const usersRef = await admin //Works Perfectly, I get the QuerySnapshot of the collection
.firestore()
.collection('Users')
.get();
console.log('usersRef: ', usersRef);
const userDocs = await Promise.all(usersRef); //This gives the error
console.log('User Docs: ', userDocs);
} catch (err) {
console.log('err: ', err);
}
return null;
});
我在Promise.all()
中传递QuerySnapshot Promise时遇到此错误:
//Error
TypeError: undefined is not a function
at Function.all (<anonymous>)
at exports.scheduledFunction.functions.pubsub.schedule.onRun (/srv/index.js:624:38)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
我希望从Promise.all()
的结果中收集所有文档ID
非常感谢您的帮助。
答案 0 :(得分:2)
Promise.all()兑现了一系列承诺。 usersRef
既不是数组,也不是诺言。由于您已经在等待get()返回的诺言,因此使usersRef
成为QuerySnapshot对象,该对象立即可用,因此您需要按照这些条款使用它。由于它是快照而不是参考,因此您可能应该使用不同的名称。例如:
const usersSnapshot = await admin
.firestore()
.collection('Users')
.get();
const usersDocs = usersSnapshot.docs
console.log(usersDocs)
usersSnapshot.forEach(doc => {
console.log(doc)
})
答案 1 :(得分:1)
不需要await Promise.all
,因为您已经使用get()
和await
在第一条语句中加载了所有用户文档。
所以应该是:
const usersDocs = await admin
.firestore()
.collection('Users')
.get();
console.log('User Docs: ', userDocs);