Firebase - Firestore - 使用collection.add()获取密钥

Wan*_*lle 16 firebase google-cloud-firestore

我正面临来自Firebase的新Firestore的问题.

情况:我有一个collection('room')

我创造了房间 collection('room').add(room)


我正在尝试做什么:我需要更新一个房间.

为此,我使用: collection('room').doc(ROOM_ID).update(update)

所以我需要在我的集合中的文档中添加ROOM_ID:

|room
    ROOM_ID
        id:ROOM_ID,
        someContent: ForTheQuery
Run Code Online (Sandbox Code Playgroud)

有可能实现这一目标吗?

另一种方法是使用以下命令创建自己生成的ID:

collection('room')
.doc(someId)
.set({
    id: someId,
    someContent: ForTheQuery
});
Run Code Online (Sandbox Code Playgroud)

但我想避免它.

Dou*_*son 41

您可以使用doc()创建对具有唯一ID的文档的引用,但不会创建该文档.然后,您可以使用文档参考中提供的唯一ID来设置该doc的内容:

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"}
    })
})
Run Code Online (Sandbox Code Playgroud)

  • @Tom在需要文档的唯一ID参与自动反序列化时可以派上用场。因此,如果您有一个JavaBean对象,其中文档ID应该是该对象的属性之一,这将安排该属性在该对象中自动设置。这样可以避免为每次反序列化而编写额外的代码。 (2认同)
  • 两个函数是否可以提取相同的 id?在这种情况下,数据完整性也可能受到损害。 (2认同)
  • @LMGagne 为同一集合中的文档生成两个相同 ID 的可能性非常低。如果你担心它,你就是在把你的精力放在错误的担忧上! (2认同)

Die*_*cio 9

ANGULARFIRE:

在添加数据库之前获取ID:

var idBefore =  afs.createId();
    console.log(idBefore );
Run Code Online (Sandbox Code Playgroud)

ANDROID FIRESTORE:

String idBefore = db.collection("YourCol").document().getId();
Run Code Online (Sandbox Code Playgroud)