【问题标题】:Cloud function: No document found云功能:未找到文档
【发布时间】:2020-01-21 10:43:08
【问题描述】:

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

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);
    });

我在这里做错了吗?

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    我了解到您想从路径'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;
    
        //....
    
    });
    

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

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


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

    【讨论】:

    • 感谢您的 cmets。事实上,我设法用 snap.data() 获得了正确的 colId。我使用此 colId 使用 WHERE 子句在另一个集合中搜索文档,但它没有找到该文档,尽管它存在。然后我从 'doc.exist' 更改为 '!doc.empty' 然后它起作用了。但是,当我尝试使用“doc.data()”从文档中获取数据时,它说 doc.data 不是函数。当我尝试使用“transSnapshot.set(data)”之类的东西将新文档插入集合时发生了同样的事情,它说“transSnapshot.set”不是一个函数!
    • 当您执行tracksRef.where('otherId', '==', colId).get() 时,您正在创建一个查询,因此,您获得的快照是QuerySnapshot 而不是DocumentSnapshot。你需要使用forEach 如图here
    • 或者,如果您 100% 确定查询只返回一个文档,您也可以这样做 doc = transSnapshot.docs[0]
    • 非常感谢。如果没有找到文档,那么我需要将新文档插入到当前集合中。我怎样才能做到这一点?我使用“db.collection('users/{userId}/othercollection').doc(colId).set(new_doc)”,但它不起作用。没有插入文档!
    • 是的,这应该可以,new_doc 是文档的字段和值的映射。如果您在这部分代码中遇到任何问题,您可能会提出新问题。如果您认为我的回答为您解决了最初的问题,请接受它(通过单击答案旁边的“检查”按钮(如 v):当它变为绿色时,表示您接受了答案。)。谢谢!
    猜你喜欢
    • 2021-03-27
    • 2019-03-28
    • 2018-08-07
    • 2023-02-03
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2019-09-09
    相关资源
    最近更新 更多