firestore 云功能更新另一个文档

firestore cloud function update another document

我想增加集合项中文档 (item_id) 中“投票”字段的值。每次将新文档添加到集合投票时,我都希望云功能为我执行此操作。新文档包含 item_id。有谁知道我该怎么做?这就是我现在拥有的:

    import * as functions from "firebase-functions";
    import * as admin from "firebase-admin";
    admin.initializeApp();

    export const vote = functions.firestore.document("/Votes/{vote}")
    .onCreate((snapshot, context) => {
      const item = context.params.item_id; 
      const itemdoc = admin.firestore().collection("items").doc(item);

      itemdoc.get().then((doc) => {
        if (doc.exists) {
          itemdoc.update({
            "votes": admin.firestore.FieldValue.increment(1)})
              .catch((err) => {
                console.log("Error updating item vote", err);  
              });
        }
      });
    });

在 firebase 控制台日志中,路径必须是非空字符串。有谁知道我做错了什么?由于路径不应该为空。

以下应该可以解决问题:

export const vote = functions.firestore.document("/Votes/{vote}")
    .onCreate((snapshot, context) => {

        const item = snapshot.data().item_id;
        const itemDocRef = admin.firestore().collection("items").doc(item);
    
        return itemDocRef.update({
            "votes": admin.firestore.FieldValue.increment(1)
        });

    });

您需要在 snapshot 上使用 data() 方法,以获取新文档的 JavaScript 表示。然后你拿 item_id 属性.

另一种可能是使用get()方法,如下:

const item = snapshot.get("item_id");

我建议将 itemdoc 变量重命名为 itemDocRef,因为它是 DocumentReference.


根据您的评论更新:

如果您想在更新后阅读项目文档,请执行以下操作:

export const vote = functions.firestore.document("/Votes/{vote}")
    .onCreate(async (snapshot, context) => {
        const item = snapshot.data().item_id;
        const itemDocRef = admin.firestore().collection("items").doc(item);

        await itemDocRef.update({"votes": admin.firestore.FieldValue.increment(1)});

        const itemDocSnapshot = await itemDocRef.get();

        //Do whatever you want with the Snapshot
        console.log(itemDocSnapshot.get("user_id"));
        
        // For example update another doc
        const anotherDocRef = admin.firestore().collection("....").doc("....");

        await anotherDocRef.update({"user_id": itemDocSnapshot.get("user_id")});
        
        return null;

    });

注意 asyncawait 关键字的使用。

const item = context.params.item_id; 

通过访问 context.params,您试图在 .document("/Votes/{vote}") 中找到通配符中的值,该值肯定未定义。要从文档中读取一个字段,试试这个:

const {item_id} = snapshot.data()
// Getting item_id using Object destructuring

if (!item_id) {
  // item_id is missing in document
  return null 
}

const itemdoc = admin.firestore().collection("items").doc(item_id);
// Pass item_id in doc                                    ^^^^^^^

您可以在 documentation. The first parameter snapshot is the QueryDocumentSnapshot which contains your doc data and the second parameter context is EventContext 中阅读有关 onCreate 的更多信息。