本文介绍了具有多个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

还有

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

When using transactions, note that:

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

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参考中: https://cloud.google.com/nodejs/docs/reference/firestore/0.13.x/Transaction ?authuser = 0#getAll

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交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:21