Firebase云功能不会从forEach返回任何信息?

时间:2018-11-20 19:08:15

标签: javascript firebase firebase-realtime-database google-cloud-functions

当我的触发器收到更新时,我试图通过admin sdk遍历另一个节点,以使用通配符{itemId}的匹配键来迭代快照的结果。由于某种原因,我的forEach似乎什么也没做,而且我也不知道为什么。我已经尝试解决这个问题已有一段时间了。查询我的firebase数据库从来没有问题,但是现在我尝试在云函数中进行查询,我一点都没有运气。我根本不知道这是否与firebase-admin有关吗?

这是我的代码,我留下了一些评论,向您展示了我试图更清楚地完成的事情:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

// admin.initializeApp();
//is this enough or do I need to add more configuration???
admin.initializeApp(functions.config().firebase);


exports.itemUpdate = functions.database
  .ref('/items/{itemId}')
  .onUpdate((change, context) => {
    const before = change.before.val();
    const after = change.after.val();

    console.log(after); //data I want to use to update query results


    //if (before === after) {
      //console.log('data didnt change')
      //return null;
    //}

admin.database().ref('users')
  .orderByChild('likedItems')
  .equalTo(context.params.itemId)
  .once('value')
  .then(snapshot => {
    //I am able to log the snapshot, but the data is misleading???
    console.log(snapshot);
    //I am trying to look for the likedItems that match the itemId (wild card)
    //from my query - Why wont anything log? Is is a problem with my admin?
    snapshot.forEach((childSnapshot) => {
      var key = childSnapshot.key;
      var targetItem = context.params.itemId; //item(s) to update
      var child = childSnapshot.child;
      var childData = childSnapshot.val();
      //attempt to update childData that match the targetItem (that was originally updated)
      //targetItem returns undefined here but when i log it its not undefined?

      return childData.likedItems.targetItem.update(after);
  });
    return;
  }).catch(error =>{
    console.log(error);
  });
});

这里是我的数据库结构的外观,然后是用户节点中的LikedItems:

    "items" : {
        "Item1" : {
          "title" : "title1",
          "type" : "type1"
        },
        "Item2" : {
          "title" : "title2",
          "type" : "type2"
        },
        "Item3" : {
          "title" : "title3",
          "type" : "type3"
        },
        "Item4" : {
          "title" : "title4",
          "type" : "type4"
        },
        ...
        ...
        ...
      },
      "users" : {
        "EoAhYX3mYcRASr5oPD1eSZ979Vr1" : {
          "followerCount" : 4,
          "followingCount" : 2,
          "likedItems" : {
            "Item1" : {
              "title" : "title1",
              "type" : "type1"
            },
            "Item10" : {
              "title" : "title10",
              "type" : "type10"
            },
            "Item12" : {
              "title" : "title12",
              "type" : "type12"
            }
          },
          "username" : "user1"
        },
        ...
        ...
        ...
    }

我非常感谢我能提供的所有帮助/建议!

干杯。

0 个答案:

没有答案