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