【问题标题】:Firebase Cloud Functions does not create document in a subcollectionFirebase Cloud Functions 不会在子集合中创建文档
【发布时间】:2020-10-01 22:44:09
【问题描述】:

当我在 Flutter 应用中使用 Firebase Cloud Functions 在集合中创建文档时,它可以工作:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.onCreatePost = functions.firestore
    .document("/posts/{postId}")
    .onCreate(async (snap, context) => {
        const doc = snap.data()
        const creatorId = doc.creatorId
        admin.firestore().collection('feeds').doc(creatorId).set({ 
                  Id: creatorId, 
                  isRead: false, 
                  timestamp: admin.firestore.FieldValue.serverTimestamp(), 
            })
        });

但是当我尝试在该文档的子集合中添加相同的文档时,它不起作用:

const functions = require('firebase-functions');
const admin = require('firebase-admin'); 
exports.onCreatePost = functions.firestore
    .document("/posts/{postId}")
    .onCreate(async (snap, context) => {
        const doc = snap.data()
        const creatorId = doc.creatorId
        admin.firestore().collection('feeds').doc(creatorId).collection('feedItems').doc(context.params.postId).set({ 
                  Id: creatorId, 
                  isRead: false, 
                  timestamp: admin.firestore.FieldValue.serverTimestamp(), 
            })
        });

我做错了什么?我确实在日志中看到云功能已成功完成,但我的 Cloud Firestore 中没有创建文档。

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

    我希望这两个函数都不能可靠地工作,因为您没有返回在异步工作完成后解析的承诺。如果您不返回承诺,则 Cloud Functions 可能会在您的函数完成之前终止它。

    至少,您应该返回由set() 返回的承诺。

    return admin.firestore()
      .collection('feeds')
      .doc(creatorId)
      .collection('feedItems')
      .doc(context.params.postId)
      .set(...)
    

    您还应该检查 Cloud Functions 日志是否有错误。由于代码完全在其外部运行,因此错误不会显示在您的应用中。

    我也建议reviewing the documentation

    【讨论】:

    • 我也试过了。但也没有用。我知道没有返回,它是不可靠的,但它确实适用于仅将文档添加到集合,而不是子集合。我还添加了一个 .then(()=> { return console.log('Write succeeded!');});到带有“return”的版本,云功能控制台确实显示消息“写入成功!”..但我没有在云 Firestore 中看到该文档。我也没有在云功能日志中看到任何错误
    • 啊..我知道发生了什么..文档正在创建,但由于 mu Flutter 代码中的另一个逻辑,它被立即删除。不过感谢您的帮助!
    猜你喜欢
    • 2018-03-29
    • 2023-03-31
    • 2018-01-02
    • 2021-02-20
    • 2022-01-17
    • 1970-01-01
    • 2020-01-12
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多