【发布时间】:2021-01-03 01:55:42
【问题描述】:
我尝试使用 .get() 查询 Firestore:
//Cloud function to perform leaderboard calculation
exports.scheduledLeaderboardFunction = functions.pubsub.schedule('00 21 * * *')
.timeZone('America/Los_Angeles')
.onRun(async (context) => {
var globalPostsArray = [];
try {
await admin.firestore()
.collection('globalPosts')
.get()
.then((querySnapshot) => {
if(querySnapshot.exists) {
querySnapshot.forEach((res) => {
const {
//Fields
//Removed
} = res.data();
globalPostsArray.push({
//Fields
//Removed
});
});
}
else {
throw new Error("Data doesn't exist") <-------- This error is thrown
}
return null
})
.then(() => {
if (globalPostsArray.length > 0) {
console.log(globalPostsArray)
}
else {
throw new Error("length not greater than 0")
}
return null;
})
}
catch(error) {
console.log(error);
}
return null;
});
但在 firebase 云日志中,我打印出以下错误:
Error: Data doesn't exist
这意味着当我使用 .get() 时 querySnapshot 不存在(抛出错误)。
globalPosts,我正在查询的集合,不为空
如果我可以让 .get() 工作,那将解决我的问题,因为我不等待更新,而这正是 .onSnapshot() 的好处。
总结:onSnapshot() 用于从 Firestore 获取数据,但我不能使用 .then() 来等待数据,因此我可以完成工作。 get() 不起作用,但如果它起作用,我可以使用 .then() 等待收集。
如何解决我的问题?
编辑:将功能更改为此,但仍然无法正常工作
//Cloud function to perform leaderboard calculation
exports.scheduledLeaderboardFunction = functions.pubsub.schedule('00 21 * * *')
.timeZone('America/Los_Angeles')
.onRun(async (context) => {
try {
await admin.firestore().collection('globalPosts').orderBy("date_created", "desc")
.get()
.then(function(querySnapshot) {
if(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
return null
}
else {
throw new Error("Data doesn't exist")
}
})
}
catch(error) {
console.log(error);
}
return null;
});
证明 globalPosts 不为空:
同样的错误:
Error: Data doesn't exist
【问题讨论】:
-
传递给
onSnapshot的函数发生在未来的某个时间点,即最终获取数据时,然后在数据更改时可能更多。您在该回调中有来自 Firestore 的数据,为什么不能在onSnapshot中进行计算? -
等一下,这是云功能吗?您无法打开侦听器并让它在无服务器功能中保持打开状态。函数不应该是持久的。
-
是的,我首先使用了 onSnapshot,但后来认为 get() 可能是要走的路。使用 get(),我的请求抛出了错误。 @windowsill 真的很奇怪,因为我在前端的许多其他地方都使用了 get() 并且没有遇到这个问题,但是我在云函数中使用 get() 时遇到了问题
标签: node.js react-native google-cloud-firestore google-cloud-functions