我是否要在 Firestore 文档中自动生成一个值?



我的文档需要一个整数值,用作查询的索引。每个文档都包含一个索引字段(数字(,我在其中手动逐个分配值。也许我可以在某个地方放置一些东西来存储当前索引值并将其递增,并在创建新文档时将其作为索引值分配给新文档。

Cloud Firestore 中没有这样的功能。 您需要自己提出所有值。 Firestore 唯一可以为您自动生成的是基于服务器时间感的时间戳。

我可以想到两种方法来解决这个问题,尽管我不知道您想对文档 ID 使用基于整数的索引。如果删除一个索引,则索引现在已关闭。那么写入失败呢?比赛条件?等。你可能想重新考虑你的数据结构和组织。

如果不需要使用整数作为文档 ID:

// Create a reference to a new document inside your collection
const ref = firebase.firestore().collection('myCollectionName').doc()
// Now you have an auto-generated document id you can use for your code
const myData = {...}
const setDoc = await firebase.firestore().collection('myCollectionName').doc(ref.id).set(myData)

如果需要使用整数:

您需要一个单独的集合/对象来跟踪最新索引,这样就不会遇到冲突。然后,您需要递增该值以获取下一个索引,然后将其用作您的 id。这带来了固有的问题,例如...如果在您尝试输入数据时数据不正确,但在您增加值后该怎么办......等。

// Collection: myIndex
// Doc: index
// Value: {lastIndex: 1}
const doc = await firebase.firestore().collection('myIndex').doc('index')
// You now have the last index value using:
const lastIndex = doc.val().lastIndex
const nextIndex = lastIndex + 1
const myData = {...}
// Now run a batched operation to write to both documents
const batch = firebase.firestore().batch()
// Update the index document
const indexUpdateRef = firebase.firestore().collection('myIndex').doc('index')
batch.update(indexUpdateRef, {lastIndex: nextIndex})
// Add your new myData document
const newDataRef = firebase.firestore().collection('myCollectionName').doc(nextIndex)
batch.set(newDataRef, myData)
// Commit the batch
await batch.commit()

正如我所说 - 我认为这是一个非常糟糕的主意和工作流程,但它是可行的。保持同步也缺少很多东西。

在上述任一情况下...

您可以利用FieldValue.increment()来帮助自动增加整数值,但这会增加更多的读取和写入,更长的处理时间和更高的费用。这就是为什么我开始并坚持认为,如果你想要自动增量索引,你可能应该重新考虑你的数据结构或考虑RDB。

最新更新