node.js - 将文档 ID 作为字段 ID 包含在 firestore 中

标签 node.js firebase google-cloud-platform google-cloud-firestore google-cloud-functions

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

示例:

documents:       data:

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

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

1:使用云函数并具有 onCreate 监听器,每次有新文档时都会抓取文档并设置 id 字段并更新它,这就是我的做法

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

它们都有效,但我的问题是我可以依赖这种操作吗?我的意思是,如果 id 以任何方式未定义,它都可能会在应用程序中进一步导致错误。

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

最佳答案

请参阅底部的 JS SDK v9 语法

有一种更简单的方法可以实现这一点,即使用 doc()方法,如下(这里使用的是JavaScript SDK v8)

var newDocRef = db.collection('collectionname').doc();
newDocRef.set({
                 name:'Jhon Doe',
                 job:'Programmer',
                 id: newDocRef.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 中找到类似的方法,here适用于 Android 和 here适用于 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
       }
   )

关于node.js - 将文档 ID 作为字段 ID 包含在 firestore 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823739/

相关文章:

node.js - 基于 Rabbitmq key 的身份验证

swift - Firebase Auth Check 返回一个用户,即使那里(绝对)不应该是一个用户

node.js - 无法将文件上传到谷歌云存储

google-cloud-platform - 无法将磁盘镜像导入 Google Cloud Platform

google-cloud-platform - 如何使用 API 在 GCP 数据流中检索当前工作人员计数

javascript - node.js 的可折叠/可扩展浏览器样式控制台?

javascript - 使用 node.js 和 ES6/ES7 功能逐行读取 CSV 文件

javascript - Chrome 显示 "Resource interpreted as Stylesheet but transferred with MIME type text/html"

firebase - 如何增加 Cloud Firestore 中的现有数字字段

javascript - 在 Lambda 函数中使用 Firebase API AWS