gpt4 book ai didi

node.js - 云函数: No document found

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:30 27 4
gpt4 key购买 nike

我正在使用云功能来检查特定文档是否存在,但它不起作用。即使有也没有找到文件。代码如下:

exports.onUserAppCreated = functions.firestore.document('users/{userId}/first_col/{colId}')
.onCreate((snap, context) => {
const data = snap.data();

const colId = data.colId;
console.log(colId);
var docRef = db.collection('users/{userId}/somecollection');

let query = docRef.where('colId', '==', colId).get().then(doc => {
if (doc.exists) {

console.log("Document data:", doc.data());
let tracksRef = db.collection('users/{userId}/othercolllection');
tracksRef.where('otherId', '==', colId).get()
.then(transSnapshot => {
if (!transSnapshot.exists) {


transSnapshot.ref.set({
otherId: colId,
time:admin.firestore.FieldValue.serverTimestamp()
});
}
return transSnapshot;
}).catch(error => {
console.log(error);
//response.status(500).send(error);
})
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
return;
}
return doc;
}).catch(function(error) {
console.log("Error getting document:", error);
});

我在这里做错了什么吗?

最佳答案

我了解您希望从路径 'users/{userId}/first_col 中的 {colId} 通配符获取 colId 的值/{colId}'。您应该使用 context对象如下:

exports.onUserAppCreated = functions.firestore.document('users/{userId}/first_col/{colId}')
.onCreate((snap, context) => {
const data = snap.data();

const colId = context.params.colId;

//....

});

请注意,snapDocumentSnapshot对应触发云函数的文档。因此,snap.data() 为您提供了一个包含该文档字段的对象,因此 data.colId 未定义(除非您已保存文档中 colId 字段中的文档 ID)。

另请注意,您可以通过执行 snap.id 通过 snap 对象获取 colId 的值,但对于其他通配符,即userId,您将需要使用context.params

<小时/>

此外,请注意,您没有考虑 Admin SDK 的异步方法(get()set( ))。 正确返回这些 promise 非常重要,请参阅相应的 doc

关于node.js - 云函数: No document found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59839305/

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