具有多个get的Firestore交易 [英] Firestore transaction with multiple get

查看:51
本文介绍了具有多个get的Firestore交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用可变数量的读取操作来运行事务. 我把read()操作放在了update()之前.

I'm trying to run a transaction with a variable number of read operations. I put the read () operations before than update ().

https://cloud.google.com/firestore上阅读Firestore文档/docs/manage-data/transactions

事务由任意数量的get()操作以及随后的任意数量的写操作(例如set(),update()或delete())组成"

"A transaction consists of any number of get() operations followed by any number of write operations such as set(), update(), or delete()"

还有

使用交易记录时,请注意:

When using transactions, note that:

  • 读取操作必须先于写入操作.
  • 如果当前的编辑影响文档的内容,则调用事务的函数(事务函数)可能会运行多次. 交易读取.
  • 交易功能不应直接修改应用程序状态.
  • Read operations must come before write operations.
  • A function calling a transaction (transaction function) might run more than once if a current edit affects a document that the transaction reads.
  • Transaction functions should not directly modify application state.

但未提供实现. 当我尝试运行下面的代码时,我发现交易功能运行了更多的时间,然后我获得了异常. 但是,如果我只尝试一种,一切都会顺利.

But is not provided an implementation. When I try to run the code below, I get that the transaction function is runned more time and then I obtain an exception. But if I try with only one get all goes OK.

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');
         });
    });

推荐答案

Firestore文档没有这么说,但是答案隐藏在API参考中:

The Firestore doc doesn't say this, but the answer is hidden in the API reference: https://cloud.google.com/nodejs/docs/reference/firestore/0.13.x/Transaction?authuser=0#getAll

您可以使用Transaction.getAll()而不是Transaction.get()来获取多个文档.您的示例将是:

You can use Transaction.getAll() instead of Transaction.get() to get multiple documents. Your example will be:

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'));

这篇关于具有多个get的Firestore交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆