Firebase Firestore事务返回的是querySnapshot而不是documentSnapshot

时间:2018-08-20 23:47:19

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

我正在从Google Cloud Functions中的Firebase文档复制此代码:

var cityRef = db.collection('cities').doc('SF');
var transaction = db.runTransaction(t => {
  return t.get(cityRef)
  .then(doc => {
    // Add one person to the city population
    var newPopulation = doc.data().population + 1;
    t.update(cityRef, { population: newPopulation });
  });
}).then(result => {
  console.log('Transaction success!');
}).catch(err => {
  console.log('Transaction failure:', err);
});

但是我得到:property 'data' does not exist on type 'QuerySnapshot'应该是documentSnapshot。

1 个答案:

答案 0 :(得分:0)

在github上打开一个问题并获得一些见解https://github.com/firebase/firebase-admin-node/issues/344

后,我找到了答案
async function setCounts(storeRef: admin.firestore.DocumentReference) { // Type here

  var transaction = admin.firestore().runTransaction(t => {
    return t.get(storeRef)
    .then((doc: admin.firestore.DocumentSnapshot) => { // Type here
      x = doc.data(); // Now i can get data() from the doc
    });
  }).then(result => {
    console.log('Transaction success!');
  }).catch(error => {
    console.log('Transaction failure:', error);
  });

}

我最终通过明确声明DocumentReference和DocumentSnapshot的类型来使其工作,我不知道为什么,但是在将linter推断的文档部署为QuerySnapshot时,即使不是这样。