首页 > 解决方案 > Firebase:未定义 Firestore 事务?

问题描述

我是 Firebase 的新手,正在阅读文档来学习。

我目前使用的是 Firestore 而不是数据库,老实说,我不太确定每种方法的优缺点。

在他们用于读取和写入数据到数据库的教程中,他们有以下关于事务的代码:

function toggleStar(postRef, uid) {
  postRef.transaction(function(post) {
    if (post) {
      if (post.stars && post.stars[uid]) {
        post.starCount--;
        post.stars[uid] = null;
      } else {
        post.starCount++;
        if (!post.stars) {
          post.stars = {};
        }
        post.stars[uid] = true;
      }
    }
    return post;
  });
}

stars在这种情况下,这旨在减轻变量的竞争条件/损坏。

我的问题是 Firestore 相当于transaction什么

import firebase from 'firebase'


const postId = 1
const firestorePostRef = firebase.firestore().collection('posts').doc(postId)

// throws an error that firestorePostRef.transaction is not defined
firestorePostRef.transaction( (post) => {
  if (post) {
    // ...
  }
})

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


Firebase Firestore 具有相同的功能。读取数据并在同一操作中写入以下内容:

// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");

db.runTransaction(function(transaction) {
    return transaction.get(sfDocRef).then(function(sfDoc) {
        if (!sfDoc.exists) {
            throw "Document does not exist!";
        }

        var newPopulation = sfDoc.data().population + 1;
        if (newPopulation <= 1000000) {
            transaction.update(sfDocRef, { population: newPopulation });
            return newPopulation;
        } else {
            return Promise.reject("Sorry! Population is too big.");
        }
    });
}).then(function(newPopulation) {
    console.log("Population increased to ", newPopulation);
}).catch(function(err) {
    // This will be an "population is too big" error.
    console.error(err);
});

这里是相关文档链接


推荐阅读