I'm creating a to do application for students. A student can create a new project and add some students when a new project is created, the user is automatically added as a user inside the created document.
So a new document is created in the 'projects' collection with some data like the name of the project and the deadline, .. , and a new document is created in the subcollection 'users'.
At the moment I can add a new project with a custom id, and a user with an auto generated id. But how can I also give the user a custom id? Because in my current code, I get an error:
FirebaseError: Invalid collection reference. Collection references must have an odd number of segments, but projects/secondProject/users/Stefje123 has 4.
In documentation I can see this is actually the way as the google docs describe it..
Anyone that can help me?
My function:
const createProject = async (e: any) => {
const newName = document.querySelector<HTMLInputElement>('#newName')?.value;
const newDate = document.querySelector<HTMLInputElement>('#newDate')?.value;
const newDescription = document.querySelector<HTMLInputElement>('#newDescription')?.value;
const username = auth.currentUser?.displayName;
e.preventDefault();
const project = await setDoc(doc(db, 'projects', newName), {
Name: newName,
Deadline: Timestamp.fromDate(new Date(newDate)),
Description: newDescription,
});
const user = await addDoc(collection(db, 'projects', newName, 'users', username), {
Name: auth.currentUser!.displayName,
UID: auth.currentUser!.uid,
Email: auth.currentUser!.email,
});
};
CodePudding user response:
You know that "odd number" means? You cannot call the collection function if you reference to a document. Odd number of segments in link path target a collection and even number like you have in code is for documents but you use a collection function.
Document reference:
doc(getFirestore(), "projects/someDoc/someCollection/nestedDoc")
Collection reference:
collection(getFirestore(), "projects/someDoc/someCollection")
A BAD collection reference (Not an odd number of segments in path):
collection(getFirestore(), "projects/someDoc/someCollection/someDoc")