I need to created documents and subcollections of documents like this:
So here is my code:
function Subscriptions() {
useEffect(() => {
const fetchData = async () => {
try {
const userProjectsColRef = collection(db, "users");
const newProjectDocRef = doc(userProjectsColRef);
addDoc(collection(newProjectDocRef, "experiences"), {
name: "hello",
});
} catch (err) {
console.log(err);
}
};
fetchData();
}, []);
return <div></div>;
}
export default Subscriptions;
How can I add data to the very first document created (the "data" field with "bio", "fullname", "company") ?
Right now, this code does add a subcollection named "experiences" which has a document with some data (name: "hello"). Like this:
CodePudding user response:
You need to create two documents: firstly the parent user
document and then
the experience
document which DocumentReference
is based on its parent doc's DocumentReference
(i.e. newProjectDocRef
).
const userProjectsColRef = collection(db, "users");
const newProjectDocRef = await addDoc(userProjectsColRef, {
// ...
});
await addDoc(collection(newProjectDocRef, "experiences"), {
// ...
});
Note that if you want those two writes to be done as an atomic operation, you should use a batched write.