Firestore在更新后无需读取文档数据即可获取Field.increment的值 [英] Firestore get value of Field.increment after update without reading the document data

查看:46
本文介绍了Firestore在更新后无需读取文档数据即可获取Field.increment的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以检索使用 firestore.FieldValue.increment 更新的文档字段的更新值,而无需索取该文档?

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?

这与成本无关,但出于可靠性考虑.例如,如果我想创建一个为每个订单增加的代码,则无法保证如果同时发生> = 2 个订单,如果我正确读取增量值,则将具有不同的代码在文档更新解决后,因为如果> = 2 写入发生在第一次读取之前,那么即使 nextOrderCode 具有适当的代码,至少2个文档将具有相同的代码预先增加.

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.

推荐答案

这是不可能的.如果您想知道值,则必须在更新后阅读文档.

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

如果需要控制该数字的值以防止其无效,则必须使用事务来确保该增量不会写入无效的值.在这种情况下, FieldValue.increment()不是一个好的选择.

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.

这篇关于Firestore在更新后无需读取文档数据即可获取Field.increment的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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