Firestore如何获取有组织的随机密钥?

时间:2020-02-16 17:41:08

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

我只是将数据从实时数据库迁移到Firestore并开始使用firestore,但我有一个功能在Realtime Database中进行push()并保存push()。key,所以我将其更改为add()或set()对于Firestore,但我意识到add()。id set()。id是完全随机的密钥,与Realtime Database的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()不同的无序密钥。

1 个答案:

答案 0 :(得分:0)

我搜索并阅读了文档,我意识到Firestore不提供组织密钥作为Realtime Database,但是我找到了解决方案。如果有人需要组织密钥,则必须使用时间戳并按升序或降序排序。 就像

// 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!