将文档 ID 作为字段 ID 包含在 Firestore 中



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

例:

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

我希望我 DataBSE 具有这种结构,现在我有两个想法来实现这一点

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以任何方式undefined它可能会导致应用程序中进一步错误。

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

请参阅底部的 JS SDK v9 语法

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

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

如文档中所述:

(doc()方法(获取集合中文档的文档引用 指定的路径。如果未指定路径,则自动生成 唯一 ID 将用于返回的文档引用。


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

>UPDATE FOR 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
}
)

前面的方法工作正常,但只是为了澄清

它到底是什么样子的

const { doc, collection, getFirestore, setDoc, addDoc } = require('firebase/firestore');
let collectionId = "Cars";
let docId;
let firestore = getFirestore();

async function addDocWithId() {
let collectionRef = collection(firestore, collectionId)

addDoc(collectionRef, {}).then(res => {
docId = res.id
let docRef = doc(firestore, collectionId + "/" + docId)

setDoc(docRef, {
id: docId,
car: 'Benz'
})
})
};

如何澄清

const { doc, collection, getFirestore, setDoc, addDoc } = require('firebase/firestore')
let collectionId = "Cars"
let firestore = getFirestore()
async function addDocWithId() {
let collectionRef = collection(firestore, collectionId)
let docRef = doc(collectionRef)
setDoc(docRef, {
id: docRef.id,
car: "Volvo"
})

}

如果有人对上面提供的答案没有运气,
请尝试这个 -> docref.set({ 'id':d ocref.ref.id}(。
它对我有用。下面是一个用例。

create(tutorial: any): any {
var docref = this.db.collection('invxxx').doc()
docref.set({ 'id':docref.ref.id, anotherField: 'anotherValue'});
}

最新更新