[英]How to add a sub collection to a document in firestore using react native
我是新來的本地人和 Firestore 的新手。
我試圖在一個名為組的集合中創建一個文檔(有效)。 創建后,我將獲取已創建文檔的文檔 ID,然后嘗試在其中創建一個名為 admins 的子集合,然后為當前用戶創建一個帶有 id 的文檔,然后將 isAdmin 字段設置為 true。
我不知道是我犯了一個錯誤還是邏輯不對。
我得到一個未處理的 promise 拒絕錯誤和一個 output 的 console.logs 如下所示
檢索到的文檔 ID:snPXEsZ8Bp7xQkJJtlj0
當前用戶 ID:vhZFUdJWeJXjcQHCVzVE3Y9meU33
[未處理的 promise 拒絕:類型錯誤:_firebase.db.collection('groups').doc(docId).collection('admins').doc(userId).add 不是 function。(在 '_firebase.db.collection( '組').doc(docId).collection('管理員').doc(userId).add({]
const submitGroup = async () => {
await db
.collection('groups')
.add({
userId: user.uid,
groupName: groupName,
groupImage: null,
postTime: firebase.firestore.Timestamp.fromDate(new Date()),
groupPrivacy: selectedItem,
})
.then((docRef) => {
// get & pass the doc id created above to var
const docId = docRef.id;
//pass the current user id to var
const userId = user.uid;
const addAddmins = async (docId, userId) => {
console.log('Document retreived with ID: ', docId);
console.log('Current User ID: ', userId);
await db.collection('groups')
.doc(docId)
.collection('admins')
.doc(userId)
.add({
isAdmin: true,
})
.then(() => {
//Alert success
}).catch((error) => {
console.log('Something went wrong', error)
})
}
//Call add sub collection and pass parent doc ID and current userID
addAddmins(docId, userId)
})
.catch((error) => {
console.log('Something went wrong', error)
})
}
我沒有測試此代碼,只是檢查groupId
中是否包含密鑰id
。
const submitGroup = async () => {
const userId = user.uid;
const groupId = await db.collection("groups").add({
userId: user.uid,
groupName: groupName,
groupImage: null,
postTime: firebase.firestore.Timestamp.fromDate(new Date()),
groupPrivacy: selectedItem
});
console.log("groupId:", groupId.id);
const addAdmins = await db
.collection("groups")
.doc(groupId.id)
.collection("admins")
.doc(userId)
.add({
isAdmin: true
});
};
好的,我設法弄清楚了我的問題,我不得不將 .add({}) 更改為 .set({})。 我想是因為第一個查詢已經創建了父集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.