[英]Save ID to Firestore document
我還想將文檔的 id 保存為屬性,而不僅僅是作為集合的參考。 目前我是這樣保存的:
const newSet: AngularFirestoreDocument<SetModel> = this.AngularFirestore.doc('users/' + this.navParams.data.userId);
// adding user to our ddbb
newSet.collection('sets').add(this.set)
.then(function (docRef) {
// ok
})
.catch(function (error) {
// error
});
那可能嗎? 還是我需要保存它,獲取 id 並再次更新它?
1 - 創建一個常量 ID。 2 - 在對象中設置 id。 3 - 保存
createEvent(set){
const id = this.firestore.createId();
set.id = id;
return this.firestore.doc(`users/${id}`).set(ev);
}
通過快速掃描CollectionReference.add(...)
的參考文檔,我看到add(...)
返回一個承諾。 在創建文檔之前,似乎無法獲取自動生成的 ID。
但請記住,文檔 ID 只是在統計上保證唯一的客戶端密鑰。
此代碼顯示了 JavaScript SDK 為生成 ID 所做的工作,這歸結為調用AutoId.newId()
。 您也可以在您自己的代碼中調用(或在它未公開導出的情況下包含)它,然后使用doc(myId)
而不是add()
。
如果這仍然是一個問題,這是我發現的,您需要創建一個空文檔並獲取 id,然后設置文檔內容。 在你的情況下,它會是這樣的。
const newDoc = newSet.collection('sets').doc()
const newDocRef = await newDoc.get()
現在設置整個文檔:
await newSet.collection('sets').doc(newDocRef.id).set({
docId: newDocRef.id,
// res of the document
})
我用這個來獲取我的文件:
this.itemsCollection.valueChanges()
我把它改成:
this.sets = this.itemsCollection.snapshotChanges()
現在我可以使用$key
獲取他們的 id 並更新我的文檔而無需額外的參考。
更多信息:
https://github.com/angular/angularfire2/issues/1278
編輯:這是我需要的解決方案,但不完全是我在這里尋找的
如果您的目的是在查詢集合時知道記錄的 ID,我認為這將是一個很好的解決方案。
firebase.firestore().collection('sets').get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
this.sets.push({ ...doc.data(), id: doc.id })
})
})
.catch(error => {
console.log(error)
})
這顯示了如何在文檔中設置自己的 ID,將 MY_ID 替換為您自己的 ID,然后使用 SET 命令將對象存儲到文檔中。 此函數返回void,因此您無法檢查或獲取任何回調。
db.collection("persons").doc("MY_ID").set({
name: "JOHN",
})
這個例子展示了如何在 person 集合中存儲一個 obj。 以約翰的名字命名。
這就是我最終這樣做的方式。 我創建一個文檔,然后在收到承諾后添加數據。
firebase.firestore.collection('instances').doc("WDXmpzpY1TWRIJjeBNrx")
.collection("suppliers").add({}).then(docRef
=> {
firebase.firestore.collection('instances').doc("WDXmpzpY1TWRIJjeBNrx")
.collection("suppliers").doc(docRef.id).set({
name:this.supplierForm.name,
phone:this.supplierForm.phone,
email:this.supplierForm.email,
address:this.supplierForm.address,
gstNo:this.supplierForm.gstNo,
uniqueID: docRef.id,
})
}).catch(err => {console.log(err)})
這里有其他選擇。
在 Firebase 中:
saveAlert(alert: Alert) {
const alertsCollection = this.firestore.collection<Alert>('alerts');
const id = this.firestore.createId();
alert.code = id;
return alertsCollection.doc(id).set(alert);
}
在 NodeJS 中:
app.post('/', async (req, res) => {
const data = {
code: '',
name: req.body.name,
description: req.body.description
}
const reference = db.collection('alerts').doc();
data.code = reference.id;
await reference.set(data);
res.json({ status: 'success', data: { alert: data } });
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.