iandev
iandev

Reputation: 191

Firebase v9 Firestore create document by id in React JS

How can i access to the document id?

I tried using doc().id but it doesnt work, how i can do it?

await addDoc(collection(db, 'users', currentUser.uid, 'proyects', doc().id, 'tasks'), {
            name: tarea,
            userUid: currentUser.uid,

        })

This is a capture of firestore, and i want to get the doc id of every document inside the proyects collection. And then create a collection named tasks inside of every of those documents.

This is a capture of firestore, and i want to get the doc id of every document inside the proyects collection. And then create a collection named tasks inside of every of those documents.

Upvotes: 1

Views: 1507

Answers (1)

samthecodingman
samthecodingman

Reputation: 26171

If the intention is to automatically create a new document ID using doc().id you would use:

const userProjectsColRef = collection(db, 'users', currentUser.uid, 'projects');
const newProjectDocRef = doc(userProjectsColRef);
addDoc(collection(newProjectDocRef, 'tasks'), {
  /* ... data ... */
});

This is because then first argument must be present and it must be either an instance of Firestore, CollectionReference, or DocumentReference. In order to use the automatically generated ID, you must pass in a CollectionReference.

Upvotes: 2

Related Questions