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

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

问题描述

在这里,我要实现的目标是我希望数据库中每个文档都具有唯一的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?

推荐答案

使用

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

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)和


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

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

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