【问题标题】:Get newly created document ID in firebase functions error在 Firebase 函数错误中获取新创建的文档 ID
【发布时间】:2021-11-01 20:09:36
【问题描述】:

我正在尝试获取新创建的 firestore 文档 ID 并在同一个云功能中使用它,但出现了一些错误!

这是我的云功能:

exports.createNewGroup = functions.https.onCall((data, context) => {

    if (!context.auth) {
        throw new functions.HttpsError(
            'unauthenticated',
            'only autehnticated users can make requests!'
        );
    }

    // Save a new group document and get the documents ID
    const { id } = admin.firestore().collection('groups').set(data.group);

    // Adding the group id to the groupmember object 
    data.groupMember.groupId = id;

    // Save a new groupmember document with the newly created groupid added
    admin.firestore().collection('groupMembers').set(data.groupMember);

    return 'All is created perfectly';
});

调用函数时,我的函数日志中出现此错误:

createNewGroup
Unhandled error TypeError: admin.firestore(...).collection(...).set is not a function

不知道我做错了什么,以及如何做到这一点?!?!希望得到帮助和提前感谢:-)

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions firebase-admin


    【解决方案1】:

    set() 方法存在于 DocumentReference 上,但您在 CollectionReference 上调用它。如果您尝试添加具有随机 ID 的文档,请改用 add() 方法。 add() 和 set() 都返回一个承诺,所以请确保你处理它们:

    exports.createNewGroup = functions.https.onCall(async (data, context) => {
      // Async function                             ^^^^^
      if (!context.auth) {
        throw new functions.HttpsError(
          'unauthenticated',
          'only autehnticated users can make requests!'
        );
      }
    
      const { id } = await admin.firestore().collection('groups').add(data.group);
      // await it    ^^^^^
    
      // Adding the group id to the groupmember object 
      data.groupMember.groupId = id;
    
      await admin.firestore().collection('groupMembers').add(data.groupMember);
    
      return 'All is created perfectly';
    });
    

    请注意.doc().set() 也可以用来代替.add()。两种方法是等价的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-06
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多