简体   繁体   English

如何通过云触发 Firestore 收集 function

[英]how to trigger a firestore collection via cloud function

I want to trigger a new collection (timeline collection) from the existing collection of followers collection and videos collection whenever I clicked the following button in my app.每当我在我的应用程序中单击以下按钮时,我想从现有的关注者收藏和视频收藏中触发一个新收藏(时间线收藏)。

Now the problem is that, the Cloud Function is created from the view log but the new collection (timeline collection) won't be created.现在的问题是,Cloud Function 是从视图日志创建的,但不会创建新的集合(时间线集合)。

Below is the code for the Cloud Function where I target the followers collection and the videos collection to create a new timeline collection.下面是 Cloud Function 的代码,我在其中定位关注者集合和视频集合以创建新的时间线集合。 I anticipate for your help.我期待你的帮助。

const functions = require("firebase-functions");
    const admin = require("firebase-admin");
    admin.initializeApp();
    
    // // Create and Deploy Your First Cloud Functions
    // // https://firebase.google.com/docs/functions/write-firebase-functions
    //
    // exports.helloWorld = functions.https.onRequest((request, response) => {
    //  response.send("Hello from Firebase!");
    // });
    exports.onCreateFollower = functions.firestore
      .document("/followers/{userId}/userFollowers/{userfollowerId}")
      .onCreate(async (snapshot, context) => {
        console.log("The Event has Created The Follower", snapshot.id);
        const userId = context.params.userId;
        const userfollowerId = context.params.userfollowerId;
    
        // 1) Create followed users posts ref
        const followedUserVideosCollection = admin
          .firestore()
          .collection("videos")
          .doc(userId)
          .collection("userVideos"); 
    
        // 2) Create following user's timeline ref
        const timelineVideosCollection = admin
          .firestore()
          .collection("timeline")
          .doc(userfollowerId)
          .collection("timelinePosts");
    
        // 3) Get followed users posts
        const querySnapshot = await followedUserVideosCollection.get();
    
        // 4) Add each user post to following user's timeline
        querySnapshot.forEach(doc => {
          if (doc.exists) {
            const videoId = doc.id;
            const videoData = doc.data();
            timelineVideosCollection.doc(videoId).set(videoData);
          }
        });
      });

I figured out what causes the error "querySnapshot.forEach isn't a function".我弄清楚了导致错误“querySnapshot.forEach 不是函数”的原因。 According to this answer , you need to query the collection first because get() returns a document instead of a snapshot.根据这个答案,您需要先查询集合,因为get()返回的是文档而不是快照。 Here's a sample code (see step 3):这是一个示例代码(参见步骤 3):

// 1) Create followed users posts ref
const followedUserVideosCollection = admin
    .firestore()
    .collection("videos")
    .doc("Videos 1") // I changed the value with your sample for test purposes and also because I'm not sure how you fill up this doc.
    .collection("userVideos");

// 2) Create following user's timeline ref
const timelineVideosCollection = admin
    .firestore()
    .collection("timeline")
    .doc(userfollowerId)
    .collection("timelinePosts");

// 3) Get followed users posts & Add each user post to following user's timeline
await followedUserVideosCollection.where('id', '==', 0).get().then((querySnapshot) => {
    if (querySnapshot) {
        querySnapshot.forEach(doc => {
            if (doc) {
                const videoId = doc.id;
                const videoData = doc.data();
                timelineVideosCollection.doc(videoId).set(videoData);
            }
        });
    }else {
        console.log("Document not found");
    }
}).catch((error) => {
    console.log(error);
});

A solution is to create a filter, and make sure that the document you're looking for matches the filter.一种解决方案是创建一个过滤器,并确保您要查找的文档与该过滤器匹配。 For example, a document inside the subcollection userVideos should have a field called id with value of 0.例如,子集合userVideos中的文档应该有一个名为id的字段,其值为 0。

You may have to remodel your DB to fix the line where I put a comment but this code should write the timeline collection.您可能必须改造您的数据库以修复我发表评论的行,但此代码应该编写timeline集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM