【问题标题】:Firestore how to get organized random key?Firestore如何获得有组织的随机密钥?
【发布时间】:2020-05-31 17:27:23
【问题描述】:

我刚刚将我的数据从实时数据库迁移到 Firestore 并开始使用 Firestore,但我有一个函数可以在实时数据库中 push() 并保存 push().key,所以我将其更改为 add() 或 set()对于 Firestore,但我意识到 add().id set().id 是完全随机的密钥,不像实时数据库 push().key 的组织方式就像后面的 push().key 总是在前面的 push().key 后面。我必须保存数据并且它必须像 push() 一样组织。是否有任何解决方案可以生成像 push().key 这样组织的密钥?

//I tried 2 options

//option 1
ref.add({something:something}).then((gref)=>{ref.doc(gref.id).set({key:gref.id},{merge:true})})

//option 2
var ref = db.doc();
ref.set({something:something,key:ref.id})

与 push().key 不同,两者都生成杂乱无章的键

【问题讨论】:

    标签: firebase firebase-realtime-database google-cloud-firestore


    【解决方案1】:

    我搜索、阅读了文档,发现 Firestore 没有提供有组织的密钥作为实时数据库,但我找到了解决方案。如果有人需要有组织的键,您必须使用时间戳并按升序或降序排序。 就像

    // when you want to save data..
    ref.set({timestamp:firebase.firestore.FieldValue.serverTimestamp()})
    // and if you want get data..
    db.collection('something').orderBy("timestamp", "asc").get()
    // it will sort automatically!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多