skip to Main Content

code for uploading data in firestore

Console: "Document written with ID: undefined"

try {
  console.log
  const docRef = addDoc(collection(db, "users"), {
    name: "Alan",
    //middle: "Mathison",
    //last: "Turing",
    //born: 1912
  });
  console.log('yyyyy');
  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}

Trying to add data in Firebase Firestore,

2

Answers


  1. addDoc is an asynchronous operation. You need to use the await keyword to halt execution of your code until the document is added. Otherwise docRef will not represent your document.

    try {
      const docRef = await addDoc(collection(db, "users"), {
        name: "Alan",
      });
      console.log('yyyyy');
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
    
    Login or Signup to reply.
  2. try that

    try {
      console.log
      const docRef = addDoc(collection(db, "users"), {
        name: "Alan",
        //middle: "Mathison",
        //last: "Turing",
        //born: 1912
      }).then(res => {
        console.log('yyyyy');
        console.log("Document written with ID: ", docRef.id);
      });
      
    } catch (e) {
      console.error("Error adding document: ", e);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search