如何使用 React 在 FireBase 中创建集合

Pas*_*ari 1 javascript firebase google-cloud-firestore

问题很简单。我想创建一个包含集合的文档。另一种措辞方式是我需要在文档中创建一个集合。

我需要能够在 React 中做到这一点。

视觉:集合->文档->集合

这是我需要添加代码的地方:

const addUser = async () => {
    await addDoc(usersCollectionRef, {
      name: newName,
      grade: Number(newGrade),
      role: newRole,
      hours: Number(newHours),

      //Collection Creation should go here as this is where I am making the new document.

    })
  }
Run Code Online (Sandbox Code Playgroud)

注意:这是反应而不是反应本机

Dan*_*sen 6

如果我理解正确的话,您想在刚刚在上面的代码中创建的文档中创建一个新集合。集合不能为空,因此您必须将一些数据放入集合中的文档中。可以这样做的一种方法是这样的:

const usersCollectionRef = collection(db, 'users')

const addUser = async () => {
    const document = await addDoc(usersCollectionRef, {
      name: newName,
      grade: Number(newGrade),
      role: newRole,
      hours: Number(newHours),
    })

    const newCollectionRef = collection(db, 'users', document.id, 'name of new subcollection')

    await addDoc(newCollectionRef, {
        data: 'Hello there World',
    })
  }
Run Code Online (Sandbox Code Playgroud)