简体   繁体   中英

How to get the auto-generated ID from .set() in firebase Firestore?

const docRef = await db.collection('Safes').add(data[i])

When I am using.add(data), I get the auto generated ID for that document in docRef.id . But when I change the.add() to.set() to avoid duplicates in my collection, printing the docRef.id gives the output as "undefined".

const docRef = await db.collection('Safes').doc().set(data[i])

How can I get the ID while using.set()?

set() won't give you the ID. The ID is available in the DocumentReference returned by doc() . You will want to rewrite your code more like this:

const docRef = await db.collection('Safes').doc()
const id = docRef.id
await docRef.set(data[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM