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

查看:18
本文介绍了将文档 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?

推荐答案

见底部 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指定的路径.如果没有指定路径,则自动生成返回的 DocumentReference 将使用唯一 ID.

(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
       }
   )

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

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