生成随机密钥firestore

时间:2018-04-01 05:49:41

标签: javascript firebase key google-cloud-firestore

我正在运行 FIRESTORE 数据库,我想创建一个随机密钥,与firestore相同的模式

在链接中,我找到了创建文档后调用的函数 with:' db.ref.add()'在客户端生成密钥:

https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36

我需要做这样的事情:

let key = newId()
console.log(key)
db.ref().doc(key).set(data)

4 个答案:

答案 0 :(得分:1)

使用firestore uid生成器非常容易:

const uid = admin.firestore().collection("tmp").doc().id

这可以解决问题,而无需保存一些数据

但在您的特定示例中:如果您不指定任何密钥,则它将由firestore自动生成:

await admin.firestore().collection("MY COLLECTION").doc().set(data)

答案 1 :(得分:0)

您可以使用以下算法生成唯一ID(或密钥):

function generateUUID() { // Public Domain/MIT
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
        d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

你会在那里找到许多其他算法(和讨论):Create GUID / UUID in JavaScript?

答案 2 :(得分:0)

看起来您可以只使用.add方法,而不是自己自动生成uuid。

https://firebase.google.com/docs/firestore/manage-data/add-data

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

答案 3 :(得分:-1)

目前firestore仍处于测试阶段,目前很多功能尚未面向公众开放。如果可用,您将获得文档中的参考。

如果您想立即实现它,唯一的方法是创建自己的随机算法(通常涉及时间戳)。希望这能回答你的问题。