Firestore事务 - 键入错误

时间:2018-01-21 08:23:52

标签: angular transactions google-cloud-firestore

我正在关注文档(第一个示例here),但由于某种原因我收到错误。它期望类型DocumentReference的参数,但我传入的变量是AngularFirestoreDocument<{}>类型。我似乎无法施展它。这是代码:

      //Get Pins counter
      let pathRef = 'PlaceOne/'+this.Place2;
      var pinDocRef = this.afs.doc(pathRef);

      //Run Transaction
      return this.afs.firestore.runTransaction(function(transaction){
        return transaction.get(pinDocRef).then(function(pinDoc){
          if(!pinDoc.exists){
            throw "Document does not exist!"
          }

          var newPinScore = pinDoc.data().pins + 1;
          transaction.update(pinDocRef, { pins: newPinScore });
        });
      })

给我这个错误:

Transaction error

1 个答案:

答案 0 :(得分:2)

您可以使用firebase native方法在没有angularfire的情况下实现它。

import * as firebase from 'firebase';

然后在你的功能中

let pinDocRef = firebase.firestore().collection('PlaceOne').doc(this.Place2);

  return firebase.firestore().runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(pinDocRef).then(function(pinDoc) {
        if(!pinDoc.exists){
            throw "Document does not exist!"
        }

        let newPinScore = pinDoc.data().pins + 1;
        transaction.update(pinDocRef, { pins: newPinScore });
    });
  }).then(function() {
      console.log("Transaction successfully committed!");
  }).catch(function(err) {
      console.log("Transaction failed: ", err);
  });

如果您想使用Angularfire方式尝试

var pinDocRef = this.afs.doc(pathRef).ref;

我不确定第二种方式。