简体   繁体   English

如何在 Firebase / Firestore 中创建用户时创建嵌套集合,用户可以在其中保存已添加书签的项目

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

相关问题 Firebase Firestore iOS:如何将图像保存到 Firestore 中的集合中? - Firebase Firestore iOS: How can I save images to a collection in the firestore? 如何只允许经过身份验证的用户在 Firebase Firestore 中创建集合? - How to allow only authenticated users to create a collection in Firebase Firestore? firebase/firestore 获取嵌套集合 - firebase/firestore get nested collection 如何从 Android 上的 Firebase Firestore 获取嵌套集合? - How to get nested collection from Firebase Firestore on Android? 如何检查 firebase firestore 用户数据集合为空 - how to check firebase firestore user data collection is empty Firestore,我应该为所有用户使用一个集合,还是为每个用户角色创建一个不同的集合? - Firestore, should I use a single collection for all users, or rather create a different collection for each user role? Firebase Firestore - 使用 where 子句按时间戳排序集合 - Firebase Firestore - order collection by timestamp with where clause 将 Firebase 认证用户与 Flutter 中的“用户”集合链接 - Linking Firebase Authenticated user with 'users' collection in Flutter 如何从 firestore 数据库中获取嵌套集合 - How can I get the nested collection from firestore database 如何让VIP用户在firebase和firestore中可写 - How to make VIP users writable in firebase and firestore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM