ReactJS/Firestore: 如何将子集合添加到现有的 firestore 文档

ReactJS/Firestore: how to add sub-collection to existing firestore document

我正在尝试在现有的 firestore 文档中创建一个新集合:

这是我的 firestore :

我想自动创建“通用”集合。

这是我的代码:

function App() {
  const dataGeneral = {
  email: "",
  firstname: "",
  lastname: "",
  phone: "",
  gdpr: false,
};

useEffect(() => {
  const migrateData = async () => {
    const usersCollectionRef = collection(db, "users"); //gets the root collection
    const { idUser } = await addDoc(usersCollectionRef, {}); // Creates a new document in the root collection

    const usersSubCollectionGeneralRef = collection(db,`users/${idUser}/general`); //Creates a sub collection in the just created document

    const { idGeneral } = await addDoc(usersSubCollectionGeneralRef, { dataGeneral }); //Creates a document in the newly created collection

   };
   migrateData();
  }, []);
}

how to add sub-collection to existing firestore document

您没有明确添加 sub-collection,因为 Firestore 不能有空集合。相反 sub-collections 将在将文档添加到集合时自动添加。 (如果他们不再持有任何文件,也会自动删除)

也就是说,您的代码从不存在这些属性的对象中解构 idUseridGeneral。您可能想像这样访问 属性 id

// Create a new, empty document in `users`
const usersRef = collection(db, 'users');
const user = awaitDoc(usersRef, {
  data: 'new document in users'
});

// Create a new document in sub-collection `general`
const generalRef = collection(db, `users/${user.id}/general`);
const general = awaitDoc(generalRef, {
  data: 'new document in sub-collection general'
});

您的意图可能是重命名已解构的 属性。如果是这样的话,see MDN for how to do that.

const {id: idUser } = await addDoc(...)
console.log('id of new document: ', idUser)