Home > front end >  Firestore not creating collection with custom doc ID
Firestore not creating collection with custom doc ID

Time:11-13

so, I have been trying for the past few days to add a collection with a custom document ID for about 2 days now, and I have no success.

I would like to create an analysis collection using node, but it never appears in the database. Here is my code:

const onSubmit = async (_values) => {
    setIsLoading(true);
    setError(null);

    const data = { name: '', pdfUrl: '' };
    if (name != '') {
      data['name'] = name;
      if (pdfUrl) {
        data['pdfUrl'] = pdfUrl;
        // alert(JSON.stringify(data));
        let res = await createAnalysis({ name, pdfUrl });
        console.log(res);
        alert(JSON.stringify(res));
        let json = res.then((json) => console.log(json));
        console.log(json);
      } else {
        addToast({
          title: 'No Title created',
          description: 'You must create a title to proceed.',
          type: 'error',
        });
      }
    } else {
      addToast({
        title: 'No pdf selected',
        description: 'You must selected a pdf to proceed.',
        type: 'error',
      });
    }
  };

It is supposed to execute a function, called createAnalysis. Here is the function:

const createAnalysis = async (data: {
name: string;
  pdfUrl: string;
}): Promise<any> => {
  const name = data.name;
  const pdfUrl = data.pdfUrl;
  const id = makeId(name);
  const ownerId = auth.currentUser.uid;
}
  ];
  // alert(JSON.stringify({ id, name, pdfUrl, ownerId, tools }));
  try {
    const analysisRef = await db.collection('analysis');
    const analysisDoc = await analysisRef.doc(id);
    const analysisCreate = await analysisDoc.set({
      id,
      name,
      pdfUrl,
      ownerId,
      tools,
    });
    console.log(analysisCreate);
    // alert(JSON.stringify(analysisCreate));
    return await analysisCreate;
  } catch (error) {
    // alert(JSON.stringify(error));
    console.error(error);
    return error;
  }
};

It does not even show an error, so I have no idea how to solve this issue. If anybody knows how, please let me know.

CodePudding user response:

Do you really need to create a custom id or do you just need the id to put into the database for reference?

If I'm not mistaken, you can try it:

try {
    const analysisRef = db.collection('analysis');
    const analysisDoc = analysisRef.doc();
    const analysisCreate = await analysisDoc.set({
      id: analysisDoc.id,
      name,
      pdfUrl,
      ownerId,
      tools,
    });
  • Related