从Firestore获取字段并使用它来更新另一个集合

时间:2019-07-13 21:55:12

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

有两个集合“ UserWithUidAndPoints”和“积分值”

exports.useWildcard = 
    functions.firestore.document('UserWithUidAndPoints/{userId}')
    .onWrite((change, context) => {
        const data = change.after.data();
        const previousData = change.before.data();

    admin.firestore().collection("PointsValue").doc("ADMIN12345678").get().then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
       //Use the fields from doc.data() below
        console.log('Document data:', doc.data());
      }
        })
    .catch(err => {
      console.log('Error getting document', err);
    });

如何获取“ doc.data”并在下面使用它来更新值

    admin.firestore().collection("UserWithUidAndPoints").doc(refId).update({
      "TotalRefers": admin.firestore.FieldValue.increment(1),

      "Points": admin.firestore.FieldValue.increment(doc.data.InviteX) //Here
  })
    return change.after.ref.set({
      Points: count + 25
    }, {merge: true});

});

1 个答案:

答案 0 :(得分:0)

将整个admin.firestore().collection("UserWithUidAndPoints").doc(refId).update({...})部分移动到数据所在的位置:

if (!doc.exists) {
  console.log('No such document!');
} else {
  // Move it here
  console.log('Document data:', doc.data());
}

由于更新需要来自另一个请求的数据,因此应该在上面的else块(代表成功的响应)进行