【问题标题】:Ho do I generate a value automatically in Firestore document?如何在 Firestore 文档中自动生成值?
【发布时间】:2019-09-04 18:30:46
【问题描述】:

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

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    我可以想到两种方法来处理这个问题,但我不知道您是否想为您的文档 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。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-27
        • 2019-09-10
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        相关资源
        最近更新 更多