如何获取创建的文档云函数的ID Typescript

Tai*_*aio 2 firebase typescript google-cloud-functions google-cloud-firestore

在监听新文档创建的函数中。如何获取该文档的 id

export const createUser = functions.firestore
    .document('users/{userId}/messages/{messagesID}')
    .onCreate((snap, context) => {
      // Get an object representing the document
      // e.g. {'name': 'Marie', 'age': 66}
      const newValue = snap.data();

      // access a particular field as you would any JS property
      const name = newValue.name;

      // perform desired operations ...
    });
Run Code Online (Sandbox Code Playgroud)

我猜这是在context争论中。我只是没有时间访问它

Dou*_*son 5

请查看Firestore 触发器的文档,其中解释了如何执行您想要的操作。请特别注意有关使用通配符的部分。

函数定义中的通配符userIdmessagesID花括号可以在给定的context.

const userId = context.params.userId;
const messagesID = context.params.messagesID;
Run Code Online (Sandbox Code Playgroud)

id您还可以使用文档的属性从其快照中获取文档的 ID :

const id = snap.id;
Run Code Online (Sandbox Code Playgroud)