[英]How to create a nested collection when creating a user in Firebase / Firestore where users can save bookmarked items
I want to be able to have a nested collection in firebase/firestore where I can save an authenticated users favorites.我希望能够在 firebase/firestore 中有一个嵌套集合,我可以在其中保存经过身份验证的用户的收藏夹。 I was trying to create the collection when the user is created so I can just read/write to it later but I can't figure out how to create the collection.
我试图在创建用户时创建集合,以便稍后可以读取/写入它,但我不知道如何创建集合。 I have something like this:
我有这样的事情:
//This function creates a new user. If the user already exists, no new document will be created
export const createUserDocumentFromAuth = async (
userAuth,
additionalInfo = {}
) => {
if (!userAuth) return;
const userDocRef = doc(db, 'users', userAuth.uid); //database instance, collection, identifier
const bookmarkRef = doc(db, 'users', userAuth.id, 'bookmarks'); //This triggers error
const userSnapshot = await getDoc(userDocRef);
if (!userSnapshot.exists()) {
//If user snapshot doesn't exist - create userDocRef
const { displayName, email } = userAuth;
const createdAt = new Date();
try {
await setDoc(userDocRef, {
displayName,
email,
createdAt,
...additionalInfo,
});
setDoc(bookmarkRef, { //Try to create a bookmarks collection here
favorites: []
})
} catch (error) {
console.log('Error creating user', error.message);
}
}
//if user data exists
return userDocRef;
};
I can create the user just fine but not another collection at the same time.我可以很好地创建用户,但不能同时创建另一个集合。 I also tried just creating the collection when a signed-in user clicks on the bookmark button like this but I get a type error in both cases
Uncaught (in promise) TypeError: n is undefined
every time.我也尝试过在登录用户像这样单击书签按钮时创建集合,但在这两种情况下我都会收到类型错误
Uncaught (in promise) TypeError: n is undefined
每次。
export const addBookmarkForUser = async (userAuth, showId) => {
const bookmarkRef = doc(db, 'users', userAuth.id, 'bookmarks');
try {
await setDoc(bookmarkRef, {
favorites: showId
});
}catch(error){
console.log('error creating bookmark', error.message)
}
};
I'm pretty new to Firebase / Firestore and all I want is to be able to save an item id in an array for an individual user when they click a button.我是 Firebase / Firestore 的新手,我想要的只是能够在单个用户单击按钮时将项目 ID 保存在数组中。 If saving in an array is not ideal or there is any better way to do this, I am open to any suggestions at this point.
如果保存在数组中并不理想或者有任何更好的方法来执行此操作,我现在愿意接受任何建议。
I was trying to create the collection when the user is created so I can just read/write to it later but I can't figure out how to create the collection.
我试图在创建用户时创建集合,以便稍后可以读取/写入它,但我不知道如何创建集合。
A (sub)collection is only created when you create the first document in it . (子)集合仅在您在其中创建第一个文档时创建。 There is no way to materialize an empty collection without a document.
没有文档就无法具体化空集合。
And it is normal that you get an error when using the doc()
method as follows而且使用
doc()
方法报错是正常的,如下
const bookmarkRef = doc(db, 'users', userAuth.id, 'bookmarks');
because this method is used to create a DocumentReference
and therefore you need to pass a path with an even number of path segments.因为此方法用于创建
DocumentReference
,因此您需要传递具有偶数个路径段的路径。 In you case you pass 3 segments.在你的情况下,你传递了 3 个部分。
You could very well define the CollectionReference
for the bookmarks
subcollection as follows, using the collection()
method and passing the 3 segments您可以很好地为
bookmarks
子集合定义CollectionReference
,如下所示,使用collection()
方法并传递 3 个段
const bookmarkRef = collection(db, 'users', userAuth.id, 'bookmarks');
but, until you add a document in it, it will not exist in the database.但是,除非您在其中添加文档,否则它不会存在于数据库中。
Conclusion: You will automatically create the user's bookmarks
subcollection the first time you create a bookmark for the user.结论:您将在第一次为用户创建书签时自动创建用户的
bookmarks
子集合。
For example:例如:
const bookmarksCollectionRef = collection(db, 'users', userAuth.id, 'bookmarks');
await bookmarksCollectionRef.add({ ... })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.