javascript - 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) {
// ...
}
})
解决方案
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);
});
这里是相关文档链接
推荐阅读
- heroku - 在使用 heroku 部署之前设置 nodemailer
- android - 如何在 Android Java 中处理 Webview 点击事件
- r - 无法在 Rstudio 中安装 xlsx 包。rjava,无法在 ubuntu 16.04 中加载共享对象
- jquery - 如何将 JQuery 响应数据 (Html.ActionLink) 解码为 HTML 表格元素?
- azure - 删除 Visual Studio 发布的 Azure 函数
- c++ - 如何在 C 构建上设置调试器标志?
- javascript - JavaScript 算法没有正确过滤
- scikit-learn - Scikit-learn:当 needs_threshold=True 时,哪些值默认提供给记分员?
- python - 带有 Python PILLOW 的虚线或虚线
- laravel - Laravel Webpack mix.js 无法使用扩展名 .vue 编译