最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Generating random Key firestore - Stack Overflow

programmeradmin9浏览0评论

Im running a FIRESTORE database, and i want to create a random key with the same pattern as firestore does.

In the link i found the function that is called once i create a document with: 'db.ref.add()' to generate the key in client side:

.ts#L36

I need to do something like this:

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

Im running a FIRESTORE database, and i want to create a random key with the same pattern as firestore does.

In the link i found the function that is called once i create a document with: 'db.ref.add()' to generate the key in client side:

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

I need to do something like this:

let key = newId()
console.log(key)
db.ref().doc(key).set(data)
Share Improve this question edited Apr 1, 2018 at 11:13 Renaud Tarnec 83.1k10 gold badges97 silver badges129 bronze badges asked Apr 1, 2018 at 5:49 eeerrrttteeerrrttt 6162 gold badges9 silver badges25 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

it is very easy to use the firestore uid generator:

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

this would do the trick without requiring to save some data

but in your specific example: if you don't specify any key it will be auto-generated by firestore:

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

Looks like you can just use the .add method instead of auto generating a uuid on your own.

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);
});
发布评论

评论列表(0)

  1. 暂无评论