[英]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.