Firestore get value of Field.increment after update without reading the document data

ぃ、小莉子 提交于 2020-01-14 15:05:47

问题


Is there a way to retrieve the updated value of a document field updated using firestore.FieldValue.increment without asking for the document?

var countersRef = db.collection('system').doc('counters');

await countersRef.update({
    nextOrderCode: firebase.firestore.FieldValue.increment(1)
});

// Get the updated nextOrderCode without asking for the document data?

This is not cost related, but for reliability. For example if I want to create a code that increases for each order, there is no guaranty that if >= 2 orders happen at the same time, will have different codes if I read the incremental value right after the doc update resolves, because if >= 2 writes happen before the first read, then at least 2 docs will have the same code even if the nextOrderCode will have proper advance increment.


回答1:


It's not possible. You will have to read the document after the update if you want to know the value.

If you need to control the value of the number to prevent it from being invalid, you will have to use a transaction instead to make sure that the increment will not write an invalid value. FieldValue.increment() would not be a good choice for this case.




回答2:


We can do it by using Firestore Transactions, like incremental worked before Field.increment feature:

try {
  const orderCodesRef = admin.firestore().doc('system/counters/order/codes');
  let orderCode = null;
  await admin.firestore().runTransaction(async transaction => {
    const orderCodesDoc = await transaction.get(orderCodesRef);
    if(!orderCodesDoc.exists) {
      throw { reason: 'no-order-codes-doc' };
    }

    let { next } = orderCodesDoc.data();
    orderCode = next++;
    transaction.update(orderCodesRef, { next });
  });

  if(orderCode !== null) {
    newOrder.code = orderCode;
    const orderRef = await admin.firestore().collection('orders').add(newOrder);

    return success({ orderId: orderRef.id });
  } else {
    return fail('no-order-code-result');
  }
} catch(error) {
  console.error('commitOrder::ERROR', error);
  throw errors.CantWriteDatabase({ error });
}


来源:https://stackoverflow.com/questions/56941616/firestore-get-value-of-field-increment-after-update-without-reading-the-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!