gpt4 book ai didi

node.js - 使用 Cloud Functions 从 onCreate 触发器检索 Firestore 文档

转载 作者:行者123 更新时间:2023-12-02 18:37:59 26 4
gpt4 key购买 nike

创建另一个文档时,我需要从 Firestore 文档中检索信息。当我尝试执行此操作时,我遇到了有关该函数不是异步的错误。我已经很久没有使用 javascript 了,我基本上又是一个新手了,不知道如何解决这个问题。

好的,我正在使用 Firebase Cloud Functions,并且相关函数是 Firestore .onCreate() 触发器。

触发该函数时,我设置一个 sender 变量(这是我需要检索的来自不同集合的文档 ID)

然后我尝试根据文档获取该文档。

函数的最终结果是这样的:

exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
.onCreate((snap, context) => {
// when friend request is created

data = doc.data()//get request data
sender = data["sender"]//get request sender from data

const requestRef = db.collection('User').doc(sender);
const doc = await requestRef.get();//get user data of sender
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());


}
});

当我在模拟器中运行它时,我收到此错误:

const doc = await requestRef.get();//get user data of sender
^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

我完全不知道该去哪里。

有人可以帮我解决这个问题吗?谢谢

最佳答案

await 关键字仅在 async 中有效功能。

exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
.onCreate(async (snap, context) => {
// ^^^^^
})

如果您(或需要)使用同步函数,那么您必须使用 promise chaining .

exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
.onCreate((snap, context) => {
return requestRef.get().then((snapshot) => {
if (snapshot.exists) { ... }
})
})

除此之外,变量/语句的顺序看起来不正确。使用当前代码(如原始问题中所示),您最终可能会收到错误:“在初始化之前无法访问'doc'”尝试像这样重构它:

exports.pushFriendRequestNotification = functions.firestore.document('friends/{friendID}')
.onCreate(async (snap, context) => {
// accessing data from newly created doc
const newDocData = snap.data()

// const sender = "" // ??

const requestRef = db.collection('User').doc(sender);
const doc = await requestRef.get();//get user data of sender
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})

发件人来自哪里?我刚刚在上面评论过,但如果发件人存在于新文档中,那么您可以通过以下方式访问它: const sender = newDocData.sender

关于node.js - 使用 Cloud Functions 从 onCreate 触发器检索 Firestore 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68463016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com