Cir*_*sso 9 transactions angularfire2 google-cloud-firestore
我正在尝试使用可变数量的读取操作来运行事务.我把read()操作放在update()之前.
在https://cloud.google.com/firestore/docs/manage-data/transactions上阅读Firestore文档
"事务由任意数量的get()操作组成,后跟任意数量的写操作,如set(),update()或delete()"
和
使用交易时,请注意:
- 读操作必须在写操作之前进行.
- 如果当前编辑影响事务读取的文档,则调用事务(事务函数)的函数可能会运行多次.
- 事务功能不应直接修改应用程序状态.
但是没有提供实现.当我尝试运行下面的代码时,我得到了更多时间运行事务函数,然后我获得了一个异常.但如果我尝试只有一个让一切都行.
const reservationCol = this.db.firestore.collection('reservations');
return this.db.firestore.runTransaction(t => {
return Promise.all([
t.get(reservationCol.doc('id1')),
t.get(reservationCol.doc(('id2')))]
).then((responses) => {
let found = false;
responses.forEach(resp => {
if (resp.exists)
found = true;
});
if (!found)
{
entity.id='id1';
t.set(reservationCol.doc(entity.id), entity);
return Promise.resolve('ok');
}
else
return Promise.reject('exist');
});
});
Run Code Online (Sandbox Code Playgroud)
sin*_*ohn 10
Firestore 文档没有说这一点,但答案隐藏在 API 参考中:https : //cloud.google.com/nodejs/docs/reference/firestore/0.13.x/Transaction?authuser=0#getAll
您可以使用Transaction.getAll()代替Transaction.get()来获取多个文档。你的例子是:
const reservationCol = this.db.firestore.collection('reservations');
return this.db.firestore.runTransaction(t => {
return t.getAll(reservationCol.doc('id1'), reservationCol.doc('id2'))
.then(docs => {
const id1 = docs[0];
const id2 = docs[1];
if (!(id1.exists && id2.exists)) {
// do stuff
} else {
// throw error
}
})
}).then(() => console.log('Transaction succeeded'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1796 次 |
| 最近记录: |