【问题标题】:My onCreate funciton in Functions of firebase is not creating my desired collection in the cloud databaseFirebase 函数中的我的 onCreate 函数没有在云数据库中创建我想要的集合
【发布时间】:2020-10-16 20:11:04
【问题描述】:

我刚刚在我的 index.js 函数文件 (firebase CLI) 中键入了一个代码。根据我的代码,必须在 firebase 的云数据库中创建一个时间线集合。函数运行正常,并且没有错误被部署并且即使在日志中一切正常。但是当我在我的应用中关注用户时,仍然不会在云数据库中创建时间线集合。

这是我的代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.onCreateFollower = functions.firestore
  .document("/followers/{userId}/userFollowers/{followerId}")
  .onCreate(async (snapshot, context) => {
    console.log("Follower Created", snapshot.id);
    const userId = context.params.userId;
    const followerId = context.params.followerId;

    // 1) Create followed users posts ref
    const followedUserPostsRef = admin
      .firestore()
      .collection("posts")
      .doc(userId)
      .collection("userPosts");

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

    // 3) Get followed users posts
    const querySnapshot = await followedUserPostsRef.get();

    // 4) Add each user post to following user's timeline
     querySnapshot.forEach(doc => {
      if (doc.exists) {
        const postId = doc.id;
        const postData = doc.data();
        return timelinePostsRef.doc(postId).set(postData);
      }
    });
  });

【问题讨论】:

    标签: node.js firebase flutter google-cloud-firestore google-cloud-functions


    【解决方案1】:

    由于您要并行执行可变数量的异步调用,您应该使用Promise.all(),以便等待所有这些不同的异步调用完成,然后再向 CF 平台指示它可以清理 CF。详情请见https://firebase.google.com/docs/functions/terminate-functions

    exports.onCreateFollower = functions.firestore
      .document("/followers/{userId}/userFollowers/{followerId}")
      .onCreate(async (snapshot, context) => {
        
        const userId = context.params.userId;
        const followerId = context.params.followerId;
    
        // ...
    
        // 3) Get followed users posts
        const querySnapshot = await followedUserPostsRef.get();
    
        // 4) Add each user post to following user's timeline
         const promises = [];
         querySnapshot.forEach(doc => {
            //query results contain only existing documents, the exists property will always be true and data() will never return 'undefined'.
            const postId = doc.id;
            const postData = doc.data();
            promises.push(timelinePostsRef.doc(postId).set(postData));
        });
    
        return Promise.all(promises);
    
      });
    

    【讨论】:

    • 即使使用了这种 Promise.all() 方法,问题依然存在。不是在数据库中创建集合。
    • 我已经测试了我的代码并确认它确实有效。您在 Cloud Functions 控制台中看到任何错误吗?
    • 对不起先生,这是我的错误,我刚刚再次部署了我的功能,现在您的代码正在运行。一切就绪。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-06-12
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 2020-02-20
    相关资源
    最近更新 更多