云功能:找不到文档

时间:2020-01-21 10:43:08

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

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

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

我在这里做错了吗?

1 个答案:

答案 0 :(得分:2)

我了解您想从路径colId中的{colId}通配符获取'users/{userId}/first_col/{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字段中)您的文档)。

还要注意,通过执行colId,可以通过snap对象获得snap.id的值,但是对于另一个通配符,即userId,则需要使用context.params


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