Angularfire增量交易
Angularfire Increment transaction
我在增加 post "likes" 的计数时遇到问题。以下是我现在拥有的:
addLike(pid, uid) {
const data = {
uid: uid,
};
this.afs.doc('posts/' + pid + '/likes/' + uid).set(data)
.then(() => console.log('post ', pid, ' liked by user ', uid));
const totalLikes = {
count : 0
};
const likeRef = this.afs.collection('posts').doc(pid);
.query.ref.transaction((count => {
if (count === null) {
return count = 1;
} else {
return count + 1;
}
}))
}
这显然会引发错误。
我的目标是 "like" 一个 post 并在另一个位置增加一个 "counter"。可能作为每个Pid的字段?
我在这里错过了什么?我确定我的路径是正确的..
提前致谢
您将使用 Firebase 实时数据库 API 在 Cloud Firestore 上进行交易。虽然这两个数据库都是 Firebase 的一部分,但它们完全不同,您不能在另一个数据库中使用 API。
要详细了解如何在 Cloud Firestore 上 运行 事务,请参阅文档中的 updating data with transactions。
看起来像这样:
return db.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(likeRef).then(function(likeDoc) {
if (!likeDoc.exists) {
throw "Document does not exist!";
}
var newCount = (likeDoc.data().count || 0) + 1;
transaction.update(likeDoc, { count: newCount });
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});
我在增加 post "likes" 的计数时遇到问题。以下是我现在拥有的:
addLike(pid, uid) {
const data = {
uid: uid,
};
this.afs.doc('posts/' + pid + '/likes/' + uid).set(data)
.then(() => console.log('post ', pid, ' liked by user ', uid));
const totalLikes = {
count : 0
};
const likeRef = this.afs.collection('posts').doc(pid);
.query.ref.transaction((count => {
if (count === null) {
return count = 1;
} else {
return count + 1;
}
}))
}
这显然会引发错误。
我的目标是 "like" 一个 post 并在另一个位置增加一个 "counter"。可能作为每个Pid的字段?
我在这里错过了什么?我确定我的路径是正确的..
提前致谢
您将使用 Firebase 实时数据库 API 在 Cloud Firestore 上进行交易。虽然这两个数据库都是 Firebase 的一部分,但它们完全不同,您不能在另一个数据库中使用 API。
要详细了解如何在 Cloud Firestore 上 运行 事务,请参阅文档中的 updating data with transactions。
看起来像这样:
return db.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(likeRef).then(function(likeDoc) {
if (!likeDoc.exists) {
throw "Document does not exist!";
}
var newCount = (likeDoc.data().count || 0) + 1;
transaction.update(likeDoc, { count: newCount });
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});