Firebase-Firestore-使用collection.add()获取密钥 [英] Firebase - Firestore - get key with collection.add()
问题描述
我正在使用Firebase的新Firestore遇到问题.
I am facing a problem with the new Firestore from Firebase.
情况:我有一个collection('room')
我用collection('room').add(room)
我要做什么:我需要更新房间.
为此,我使用:collection('room').doc(ROOM_ID).update(update)
因此,我需要在集合中的文档中添加ROOM_ID:
So I need to add ROOM_ID in the document in my collection:
|room
ROOM_ID
id:ROOM_ID,
someContent: ForTheQuery
有没有可能实现这一目标的方法?
Is there a possible way to achieve that?
另一种方法是使用以下方法为自己创建一个生成的ID:
An alternative is to create myself a generated ID with:
collection('room')
.doc(someId)
.set({
id: someId,
someContent: ForTheQuery
});
但是我想避免它.
推荐答案
您可以使用 doc()创建对具有唯一ID的文档的引用,但该文档尚未创建.然后,您可以使用文档参考中提供的唯一ID来设置该文档的内容:
You can use doc() to create a reference to a document with a unique id, but the document will not be created yet. You can then set the contents of that doc by using the unique id that was provided in the document reference:
const ref = store.collection('users').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})
这篇关于Firebase-Firestore-使用collection.add()获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!