在 firestore 中包含文档 ID 作为字段 ID [英] Include the document id as a field id in firestore

查看:21
本文介绍了在 firestore 中包含文档 ID 作为字段 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要实现的目标,我希望数据库中的每个文档都有一个唯一的 ID 字段,并且我希望该唯一 ID 与文档 ID 相同.

Heres what i am trying to achieve i want a unique id field for every document in my database and i want that unique id to the same as the document id.

示例:

documents:       data:

eBgdTRE123       id:'eBgdTRE123'
                 name:'Jhon Doe'
                 job:'Programmer'     

我希望我的数据库有这个结构,现在我有两个想法来实现这个

i want i databse to have this structure, now i got two ideas to achieve this

1:使用云功能并具有 onCreate 侦听器,并且每次有新文档时都会抓取文档并设置 id 字段并在此处更新它我是如何做的

1: to use cloud function and have onCreate listener and everytime theres a new document grab document and set the id field and update it heres how i am doing it

exports.addDocIdToField = 

functions.firestore.document('collectionname/{docID}').onCreate((snap,context) => {
    const id = context.params.docID;
    return admin.firestore().collection('collectionname')
        .doc(id).set({ id: snap.id }, { merge: true })
        .then(() => {
            return null;
        })
        .catch((error) => {
            return null;
        });
})

2: 使用上述方法创建文档.添加该文档后立即添加新文档获取新添加的文档并更新其 id

2: to use the above kind of method on document creation. add a new document as soon as that document is added get the newly added document and update its id

它们都可以工作,但我的问题是我可以依赖这种操作吗?我的意思是,如果 id 无论如何都是 undefined,它可能会在应用程序中进一步导致错误.

both of them work but my question is can i rely on this kind of operation? i mean if the id is by any means undefined it can cause an error further in the app.

或者是否有其他方法可以实现这一目标?

or if there are other ways to achieve this?

推荐答案

见底部 JS SDK v9 语法

有一种更简单的方法来实现这一点,使用 doc() 方法,如下(此处使用 JavaScript SDK v8)

There is a simpler way to achieve that, using the doc() method, as follows (here with the JavaScript SDK v8)

var newDocRef = db.collection('collectionname').doc();
newDocRef.set({
                 name:'Jhon Doe',
                 job:'Programmer',
                 id: newDocRef.id
          })

如文档中所述:

(doc() 方法)在集合中获取文档的 DocumentReference指定路径.如果没有指定路径,一个自动生成的唯一 ID 将用于返回的 DocumentReference.

(the doc() method) gets a DocumentReference for the document within the collection at the specified path. If no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference.


您会在其他客户端 SDK 中找到类似的方法,此处 适用于 Android 和 此处 适用于 iOS.


You will find similar methods in the other Client SDKs, here for Android and here for iOS.

JS SDK v9 更新:

import { collection, doc, setDoc } from "firebase/firestore"; 

const newDocRef = doc(collection(db, "collectionname"));
await setDoc(
       newDocRef, 
       {
         name:'Jhon Doe',
         job:'Programmer',
         id: newDocRef.id
       }
   )

这篇关于在 firestore 中包含文档 ID 作为字段 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆