skip to Main Content

I’m creating a new project within the "projects" collection with the following code:

  addProject(project:any) {
    let projectsCollection = collection(this.firestore,'projects');
    return addDoc(projectsCollection,project);
  }

I need this function to return the ID of the created document, as I need to later add a new collection within this document.
In other words, I need to receive the ID of the document that was created in the Angular service, to continue my logic, is this possible?

After creating the project I need to call this new function (function below) to add a new collection INSIDE the project created above.

  addService(service: any) {
    let projectsCollection = collection(this.firestore,'projects', (here is the ID of the project created above..), 'projectDetailService');
    return addDoc(projectsCollection,service);
  }

but I didn’t find a way to get this newly created project ID. Can anyone help me in any way? thanks

I tried different ways, all without success.

2

Answers


  1. EDIT: i just noticed the question references angular. I’m guessing angular has some firebase library that uses observables instead of promises, in which case my code examples won’t quite work.


    The promise created by addDoc resolves to a document ref, and that ref has an id:

    async someFunction() {
      const docRef = await addProject('foo');
      console.log('Doc id:', docRef.id);
    }
    

    Or if you prefer .then over async/await:

    addProject('foo')
      .then(docRef => {
        console.log('Doc id:', docRef.id);
      });
    
    Login or Signup to reply.
  2. With Firebase you can create a document without providing an id and that function is AddDocument. The other function is SetDocument which asks you to provide an id for the document and this function creates the document if it doesnt exist yet and if it already exists it will update the whole document. There are other functions like update that lets you update specific fields of the document.

    As already has been stated by you, in first instance if you are using the add function you can get a doc id by saving the result of the function in a variable like docRef. If you wanna use the set function you can create the document id with UUID or any other library and save it as a property of your object and there you go.

    Im not super aware of the apis that firebase gives to Angular users, I’ve use it with react wich provides the normal firebase functionality and with ios that gives you some specific apis but the basic operations of a crud remain the same with the add, set, update, delate functions from firebase.

    Angular example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search