![](/img/trans.png)
[英]How do I add a document reference with an auto generated ID when writing a batch in Firebase?
[英]React Native Firebase How To Have Auto Document Id Increment by 1
所以我只想自動遞增。 目前,無論我在 firebase 中的應用程序中創建什么文件,都會自動獲得大隨機 ID。 我希望集合中的每個新文檔都只有 1+ id,例如我的意思是集合中的第一個文檔獲取 id = 1,第二個文檔將自動獲取 id = 2 等等......這是我的代碼創建帖子:
addPost = async ({ text, avatar, name }) => {
return new Promise((res, rej) => {
this.firestore
.collection("posts")
.add({
text,
//text2,
//id,
uid: this.uid,
timestamp: this.timestamp,
avatar,
name,
})
.then((ref) => {
ref.update({ id: ref.id });
res(ref);
})
.catch((error) => {
rej(error);
});
});
};
我至少可以部分回答這個問題——單調變化的 ID(即遞增)在 Firestore 中是非常不鼓勵的。 這些“大型 ID”的隨機分布是大規模 Firestore 的一個基本性能特征。 如果您需要某種順序,請使用文檔中的字段,而不是文檔 ID。
我是如何解決這個問題的:我創建了一個名為“id”的新集合,並只給它一個也稱為“id”且類型為數字的字段。 我將值設為 0。秘訣是在 state 中獲取此值,並在每次我發布新帖子時遞增它(也就是每次我想在其他集合中更新我的 ID 時)。 然后對於我想要在我的其他集合中增加的 id,我使用 state 並輸入 +1。 復雜,但對於任何需要它的人來說,這里是代碼:
addPost = async ({ text, avatar, name }) => {
return new Promise((res, rej) => {
this.provjera();
this.firestore
.collection("posts")
.add({
text,
id: this.state.specialid + 1,
uid: this.uid,
timestamp: this.timestamp,
avatar,
name,
})
.then((ref) => {
console.log(this.state.specialid);
this.setState({ specialid: this.state.specialid + 1 });
this.firestore
.collection("id")
.doc("hl6ucFvzQ18lIFae9feo")
.update({ id: this.state.specialid });
//console.log(this.state.specialid);
res(ref);
})
.catch((error) => {
rej(error);
});
});
};
這是檢查方法:
check = async () => {
const yolo = [];
const snapshot = await firebase
.firestore()
.collection("id")
.get()
.then((snapshot) => {
snapshot.docs.forEach((doc) => {
const { id } = doc.data();
yolo.push({ id: id });
this.setState({ specialid: yolo[0].id }); //this gets field value of id inside collection id which is 0.
});
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.